A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

how to create a singleton class in java with example

Java Singleton class sample code examples - Java Sample Programs
Interview Question Answer for Java Developer
How to create a singleton class in Java?

Singleton class creates only one instance in entire application and program.
It means that we can’t create multiple instance of Singleton class.  Let’s See sample output of below program:
testSingleton_obj: mvc.model.TestSingleton@7852e922
testSingleton_obj1: mvc.model.TestSingleton@7852e922

Here, you are seeing same object while using to print object of class,
System.out.println(testSingleton);
System.out.println(testSingleton1);

This will print object. In the below program we have created to object as
        TestSingleton testSingleton_obj = getInstance();
        TestSingleton testSingleton_obj1 = getInstance();

Program code:

public class TestSingleton {
        
    private static TestSingleton TestObj;
    
    static{
        TestObj = new TestSingleton();
    }
    
    private TestSingleton(){
    
    }
    
    public static TestSingleton getInstance(){
        return TestObj;
    }
    
    public static void main(String a[]){
        TestSingleton testSingleton_obj = getInstance();
        System.out.println("testSingleton_obj: "+testSingleton_obj);
       
        TestSingleton testSingleton_obj1 = getInstance();
        System.out.println("testSingleton_obj1: "+testSingleton_obj1);       
    }
}

Console output:
testSingleton_obj: mvc.model.TestSingleton@7852e922

testSingleton_obj1: mvc.model.TestSingleton@7852e922

LEARN TUTORIALS

.

.