×

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 Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.