Java Singleton Pattern Hackerrank Solution

Java Singleton Pattern Hackerrank Solution
Java Singleton Pattern Hackerrank Solution

Java Singleton Pattern Hackerrank Solution

Complete the Singleton class in your editor which contains the following components:

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

Once submitted, our hidden Solution class will check your code by taking a String as input and then using your Singleton class to print a line.

Input Format

You will not be handling any input in this challenge.

Output Format

You will not be producing any output in this challenge.

Sample Input

hello world

Sample Output

Hello I am a singleton! Let me say hello world to you

Code Solution:

//Java Singleton Pattern Hackerrank Solution

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;
    }

}

//Java Singleton Pattern Hackerrank Solution

Disclaimer: This problem is originally created and published by HackerRank, we only provide solutions to this problem. Hence, doesn’t guarantee the truthfulness of the problem. This is only for information purposes.

Leave a Comment