In this HackerRank Java Singleton Pattern problem in the java programming language you need to Complete the Singleton class in your editor which contains the following components:

  1. A private Singleton non-parameterized constructor.
  2. A public String instance variable named str.
  3. Write a static method named getSingleInstance that returns the single instance of the Singleton class.


HackerRank Java Singleton Pattern problem solution


HackerRank Java Singleton Pattern problem solution.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.reflect.*;


class Singleton{
	
	static Singleton instance = new Singleton();
	
	private Singleton() {
		
	}
	
	public String str;
	
	static Singleton getSingleInstance() {
		return instance;
	}

}


Second solution

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.reflect.*;


class Singleton{
    public String str;
    private static Singleton instance;
    private Singleton() {
        
    }
    
    public static Singleton getSingleInstance () {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}


The third solution in java 8 programming.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.reflect.*;


class Singleton{
    private volatile static Singleton instance;
    public static String str;
    private Singleton() {}
    
    static Singleton getSingleInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

}