Singleton Class in Java
In object-oriented programming, we often need to create a class that can be instantiated only once at a time. We can't create the object of a singleton class more than once. However, if we try to create the object of a singleton class after the first time, the new reference variable will also point to the first instance created.
All the reference variables of a singleton class object refer to the same data since they point to a similar object. To create a singleton class in Java,
In general, we use the constructor to create the instance of the class. On the other hand, we will use the getInstance() method to get the instance of the class. Consider the following example to create the singleton class in java.
first reference: I am some other string second reference: I am some other string third reference: I am some other string
Only the first time, the value of the static variable 'instance' is null. Therefore, the object is created only once. The second time, the value of the variable 'instance' is not null, and thus, the object will not be created again, and the same object is returned.