How to Create a Singlton Class in Java by Example?

How to Create a Singleton Class in Java by Example? 

 
Singleton: Exactly one instance of a class. Define a class that has only one instance and provide a global point of access to it. 
 
Create a class singleton is very important in real-time projects. The Singleton's purpose is to control object creation, limiting the number of objects to one only. If we are creating an object of a class, again and again, that will definitely increase the memory and finally, our application will get slow.
 
For Example: If we have a restriction that we can create only one instance of a database connection. In this case, we will create only one object of the database and used it everywhere.
 
Implementation of Singleton class:
 
Singleton.java
  1. package com.java.deepak.singleton;  
  2. public class Singleton {  
  3.  private static Singleton instance;  
  4.  private Singleton() {}  
  5.  public synchronized static Singleton getInstance() {  
  6.   if (instance == null) {  
  7.    instance = new Singleton();  
  8.    System.out.println("New Object Created...!!!");  
  9.   } else {  
  10.    System.out.println("Object Already in Memory...");  
  11.   }  
  12.   return instance;  
  13.  }  
  14. }  
  • We will make constructor as private. So then we can not create an object outside of a class.
     
  • Create a private method to create an object of a class. By using this method, we will create an object outside of class.
SingletonClient.java
  1. package com.java.deepak.singleton;  
  2. public class SingletonClient {  
  3.  public static void main(String[] args) {  
  4.   Singleton s1 = Singleton.getInstance();  
  5.   Singleton s2 = Singleton.getInstance();  
  6.  }  
  7. }   
Here we are calling the singleton class two times.
 
Output:
 
output
 
In the output, we can see that when we call the method the first time then the new object will create but when we call the second time then the existing object will return.
Next Recommended Reading Wrapper Classes in JAVA