ADVERTISEMENT
ADVERTISEMENT

Java program to compare instances of singleton class

Learn how to compare instances of singleton class in Java?
Submitted by Nidhi, on March 16, 2022

Problem Solution:

In this program, we will create a singleton class. Then we will create the objects of the singleton class and compare the instances of the singleton class.

Program/Source Code:

The source code to compare instances of the singleton class is given below. The given program is compiled and executed successfully.

// Java program to compare instances of Singleton class

class Singleton {
  private static Singleton singleRef = null;

  private Singleton() {}

  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();
    Singleton obj3 = Singleton.getSingletonInstance();

    if (obj1 == obj2 && obj1 == obj3)
      System.out.println("All objects are pointing to the same memory location.");
    else
      System.out.println("All objects are not pointing to the same memory location.");
  }
}

Output:

All objects are pointing to the same memory location.

Explanation:

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

The Main class contains a static method main(). The main() is an entry point for the program. And, created the instances obj1, obj2, obj3 and compared all objects, and printed the appropriate message.

Java Class and Object Programs »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.