Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Singleton class in java
2.1.
Why do we need singleton class?
2.2.
How to make a singleton class in java?
2.3.
Syntax
2.4.
Implementation 1
2.5.
Implementation 2
3.
Frequently Asked Questions
3.1.
Why should we use singleton class?
3.2.
Which is better in Java: implementing public static methods or a singleton class?
3.3.
Can we say that the singleton class is thread-safe?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Singleton Class in java

Author Ashish Sharma
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

A class is a user-defined blueprint or prototype that is used to create objects. It represents the collection of attributes or methods shared by all objects of the same type. There are three types of variables in java classes:

Local variable: local variables are defined inside the methods, constructors, or blocks.
Instance variable:  Instance variables are variables within the class but outside of any method.
Class variable: Class variables are the variables declared within the class, outside of any method, with a static keyword.

To learn more about the classes and the Java, refer to the link.    

Java

In this article, we will discuss about the Singleton class in java, syntax, how to make a singleton class in java, and its implementation.

Also see, Duck Number in Java and Hashcode Method in Java

Singleton class in java

In Java, a Singleton class is one that enables access to it through a single instance at a time. This design approach limits unwanted class instantiation and ensures that only one class object exists at any specified instant per JVM instance. As a result of this design, any class specified as Singleton has a single instance with a global point of access to it. We cannot delete a singleton class at the end of the application's life cycle.

Why do we need singleton class?

Restricting a class's instance generation saves memory space because the object is no longer produced when a new request is made. That's why the Singleton pattern in Java is most commonly found in multi-threaded and database applications. It is mostly used for logging, caching, thread pooling, configuration settings, and other purposes.

How to make a singleton class in java?

Before jumping to the method of how to make a singleton class in java. We need to keep in mind a few points:

🔻We need to ensure that there is only one class instance.
🔻We need to provide global access to instances via

      ▶️Declaring all the class's constructors to be private.
      ▶️Including a static method that returns an instance reference.
      ▶️The instance which is stored as a private static variable.   

Now let’s move to the method of how to make a singleton class in java.

To make a singleton class, we require mainly three things:

  • A static member of the class
  • Private constructor
  • A static factory method

Syntax

// java syntax to show how to make singleton class in java
class codingninjas {

    // private field that refers to the object
    private static ninjas object;

    private ninjas() {
    // constructor of the codingninjas class
    }

    public static ninjas getInstance() {
        // write code that allows you to create only one object
        // access the object as per the need
    }
}

 

Now, let’s deep dive into the implementation of how to make a singleton class in java. Try this code on Online Java Compiler.

Know about Single Inheritance in Java in detail.

Implementation 1

// java program to show how to make singleton class in java.
class singleton {
    private static singleton singletonObject;

    private singleton() {
    }

    public static singleton getInstance() {
        singletonObject = new singleton();
        return singletonObject;
    }

    public void getConnection() {
        System.out.println("Congratulations! you have learned how to make singleton class in java.");
    }
}

class codingninjas {
    public static void main(String[] args) {
        singleton obj;

        // refers to the only object of Database
        obj = singleton.getInstance();
        obj.getConnection();
    }
}

 

Output

Output

Explanation

When we execute the getInstance() function for the first time in a singleton class, it generates the object of the class with a name single instance and returns it to variable. Because a single instance is a static variable, it is set to some object rather than null. If we attempt to call the getInstance() function again, since the single instance is not null in the example, it is returned to a variable rather than instantiating the Singleton class again. We can handle it by the if condition. We will discuss this in a further example.

Must Read Static Blocks In Java and Swap Function in Java

Implementation 2

// java program on how to make singleton class in java
class singleton {
    private static singleton singletonObject = null;

    private singleton() {
    }

    public static singleton getInstance() {
        // create object if it's not already created
        if (singletonObject == null) {
            singletonObject = new singleton();
        }

        // returns the singleton object
        return singletonObject;
    }

    public void getConnection() {
        System.out
                .println("Congratulations! you have learned how to make singleton class in java (with if condition).");
    }
}

class codingninjas {
    public static void main(String[] args) {
        singleton obj;

        // refers to the only object of Database
        obj = singleton.getInstance();
        obj.getConnection();
    }
}

 

Output

Output

Explanation

When we first execute the Singleton() function in the singleton class, it generates an object of class Singleton with the name singleobject and returns it to the variable. Because a singleobject is static here, it is changed from null to some object. If we try to call the Singleton() function again, it is returned to a variable instead of instantiating the Singleton class again.

You can also read about the Multiple Inheritance in Java.

You can also check about Singleton Design Pattern C#.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

Why should we use singleton class?

We can use singleton classes for driver objects, logging, caching, thread pool, and database connections. 

Which is better in Java: implementing public static methods or a singleton class?

It all depends on what you want. When you need the object state (e.g., polymorphism like Null state instead of null, or default state), a singleton is a nice option, whereas the static method is used when you need a function (Receive inputs then return an output).

The benefit of a singleton is that if you later determine that this object should no longer be a singleton (due to new insights or new requirements), it is easier to refactor ( we just need to change all the places that get the instance, instead of all calls to the static methods).

Can we say that the singleton class is thread-safe?

A singleton class is not thread-safe. Numerous threads can access the singleton simultaneously and generate multiple objects, which violates the concept of a singleton.

Conclusion

In this article, we have learned the Singleton class in java, syntax, how to make singleton class in java, and its implementation.

After reading about How to make singleton class in java, are you not feeling excited to read/explore more articles on java? Don't worry; Coding Ninjas has you covered. If you want to check out java-related articles, refer to the private constructor and singleton class in javaOverloading and Overriding static Methods in javaUnderstanding Association, Aggregation, and Composition in Java.


Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.


Nevertheless, you may consider our paid courses to give your career an edge over others!
Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Previous article
Comparator Interface in Java with Examples
Next article
Scanner Class in Java
Live masterclass