Please disable adblock to view this page.

← Go home

Singleton snippet (Java)

May 10, 2016
Published By : Pratik Kataria
Categorised in:

public class singleton {

	private static singleton obj;

	private singleton(){
		System.out.println("Constructor is called only once.");
	public static singleton getInstance(){
		if(obj == null){
			obj = new singleton();
		return obj;

	public int add(int i, int j){
		return (i + j);
	public int sub(int i, int j){
		return (i-j);
	public static void main( String [] args){
		singleton obj1 = singleton.getInstance();		
		singleton obj2 = singleton.getInstance();
		// 'n' number of object creation won't call constructor 'n' times. This is singleton feature.
		System.out.println(singleton.getInstance().add(5, 6));	//it is object.function() call


Constructor is called only once.

View Article Page

Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.