A walkthrough of Java Singleton class

Arpit Bhatt
2 min readApr 25, 2021

--

A singleton is a design pattern that allows the only single instance to be created in the memory.

In Java, a singleton design pattern lets us create only one instance of a class throughout the application and it ensures that a single instance present in memory(JVM).

Some rules are must be applied when we create a singleton class.

  1. A public static method to get the instance of the class from anywhere in the application.
  2. Private constructor to instantiate the object of the class.
  3. It must have a private static variable of the same class which is the only reference of the class.

Example -

Singleton class Example

output:

There are several more ways to perform modification in

  1. Eager initialization — We can create a new object at the time of declaring a variable.

private static Singleton instance = new Singleton();

2. Through static initialization block.

3. Lazy initialization — Object is created when getInstance() method is called.

You can find this code on GitHub https://github.com/arpitbhatt027/core-java-programs/blob/master/src/interview_programs/SingletonDemo.java

--

--

Arpit Bhatt
Arpit Bhatt

No responses yet