×

Singleton class in Java

What is Singleton class in Java?

Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class Abc. We can have one instance as

Abc o1 = new Abc() ; // one instance of class Abc

We can have another instance to class Abc also.

Abc o2 = new Abc() ; // instance 2 of class Abc

Here we have created two instances. That means o1 will have different values and o2 will have different values. But what if you want to create only one instance of your class? That means we are not allowed to create instance 2 ( o2 ). This means our class is Singleton class. Allowing only one instance to a class is known as Singleton class.

How to create a Singleton class?

For creating a Singleton class in Java, we have to remember a few steps.

Step 1: We have to create a static instance or a static object for the class.

class Abc
{
static Abc o1 = new Abc () ; // creating static object 
}

Here in class only we are creating its instance or object.       

Step 2: Don't allow the user to create an instance with the default constructor. That defines a constructor which is private.

public class Singleton
{
public static void main(String args[])
{
Abc o1 = new Abc () ; // calling the default constructor which is public 
}
}
class Abc
{
static Abc o = new Abc () ;
private Abc()
{


}
}

Here new Abc () is a default constructor which is by default public. But if we create a private constructor within the class, we cannot call the default constructor.

Step 3: We should create a method that should be static which will return the object of or instance of class Abc.

public class Singleton
{
public static void main(String args[])
{
Abc o1 = new Abc () ; // calling the default constructor which is public 
}
}
class Abc
{
static Abc o = new Abc () ;
private Abc()
{


}
public static Abc getObject()
{
return o;
}
} 

Here the “ lazy instantiation  “ concept is used to write the static method. Lazy instantiation is nothing, but the object creation is done according to the requirement.

That’s it if you follow these three steps, that means you are allowing only one instance of a class. 

Now, how to get an instance of a class? Since this getObject() method is a static method, we can simply say

Abc o1 = Abc.getObject () ;

At any condition or in any case, we are allowed to create only one instance of the class Abc.

public class Singleton
{
public static void main(String args[])
{
Abc o1 = Abc.getObject();
}
}
class Abc
{
public static Abc o = new Abc() ;
private Abc()
{


}
public static Abc getObject()
{
return o;
}
}

Output

Singleton class in Java

Now since object o is static. This static object will be created and will be on memory when the class is loaded so it becomes a global variable. Even if we are not using this object, it will be there in the memory. That is one of the drawbacks. If this object consumes lots of resources and if this object is bulky, it is a waste of our memory. So, this type of object creation in the Singleton class is known as early instantiation. Because if we are not using it, it will be created.

Singleton class using Lazy Instantiation

We can create the instance of a class at the time of calling the static method.

SingletonByLazy.java

public class SingletonByLazy
{
public static void main(String args[])
{
Abc o = Abc.getObject();
}
}
class Abc
{
static Abc o; // declaring the static object 
private Abc()
{


}
public static Abc getObject()
{ 
o = new Abc(); // lazy instantiation
return o;
}
}

Output

Singleton class in Java

When we say getObject() it will create a new object and it will return the object. That means if we create another object say o1, that means we are calling the getObject() method twice. So, it will create two objects. Here we lost our singleton class step 1. So, what we can do is we can just verify before creating the object. We need to verify that this is the first time we are calling our object.

SingletonByLazy1.java

public class SingletonByLazy1
{
public static void main(String args[])
{
Abc o = Abc.getObject();
}
}
class Abc
{
static Abc o; // declaring the static object 
private Abc()
{


}
public static Abc getObject()
{ 
if ( o == null ) // verifying whether object creation is null
{
o = new Abc(); // lazy instantiation
                         }
return o;
}
}

Output

Singleton class in Java

Related Topics

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.