×

Java Programs

Java Practice

Java program to create instances of singleton class and print hash codes

Learn how to create instances of singleton class and print hash codes?
Submitted by Nidhi, on March 16, 2022

Problem statement

In this program, we will create a singleton class with a constructor. Then we will create the instances of the Singleton class and print Hash codes.

Java program to create instances of singleton class and print hash codes

The source code to create instances of singleton class and print hash codes is given below. The given program is compiled and executed successfully.

// Java program to create instances of Singleton class 
// and print Hash codes

class Singleton {
  private static Singleton singleRef = null;

  private Singleton() {
    System.out.println("Hello from Singleton class");
  }

  public static Singleton getSingletonInstance() {
    if (singleRef == null)
      singleRef = new Singleton();

    return singleRef;
  }
}

class Main {
  public static void main(String args[]) {
    Singleton obj1 = Singleton.getSingletonInstance();
    Singleton obj2 = Singleton.getSingletonInstance();

    System.out.println("Obj1 Hashcode: " + obj1.hashCode());
    System.out.println("Obj2 Hashcode: " + obj2.hashCode());
  }
}

Output

Hello from Singleton class
Obj1 Hashcode: 992136656
Obj2 Hashcode: 992136656

Explanation

In the above program, we created a singleton class Singleton and public class Main. The Singleton class contains a constructor and method that returns the instance of the class.

The Main class contains a static method main(). The main() is an entry point for the program. And, created the instances obj1, obj2 and printed the hash code.

The hash code of all references of the Singleton class is the same because A singleton class is a class that can have only one object at a time.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.