Java program to create a singleton class

Demonstrate the example to create a singleton class in Java.
Submitted by Nidhi, on March 16, 2022

Problem Solution:

A class is said to be a Singleton class when it contains only one object at a time. In this program, we will create a singleton class with a constructor and methods. We can create only one object of a singleton class.

Program/Source Code:

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

// Java program to create Singleton class

class Singleton {
  private static Singleton singleRef = null;

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

  public void SayHello() {
    System.out.println("Hello world");

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

    return singleRef;

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



Hello from Singleton class
Hello world


In the above program, we created a singleton class Singleton and public class Main. The Singleton class contains constructor and two methods getSingletonInstance(), SayHello(). The getSingletonInstance() method returns instance of class. The SayHello() method prints "Hello world" message.

The Main class contains a static method main(). The main() is an entry point for the program. Here, we created the object of the Singleton class and called SayHello() method.

Java Class and Object Programs »



Comments and Discussions!





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

© some rights reserved.