Java Programming Handbook

    Singleton Class in Java

    Introduction#

    A Singleton Class in Java is a design pattern that restricts the instantiation of a class to a single instance. It ensures that only one object of the class exists in the entire application and provides a global point of access to that instance.

    Why Use Singleton Pattern?#

    • To manage shared resources like database connections or configuration settings.
    • To ensure controlled object creation and save memory.
    • To provide global access to a single instance.

    Implementing Singleton in Java (Basic Example)#

    Since we have already learned about static and final, we can use them to create a Singleton class effectively.

    class Singleton { private static final Singleton instance = new Singleton(); // Static and final instance private Singleton() { } // Private constructor to prevent instantiation public static Singleton getInstance() { return instance; // Returns the single instance } } public class Main { public static void main(String[] args) { Singleton obj1 = Singleton.getInstance(); Singleton obj2 = Singleton.getInstance(); System.out.println(obj1 == obj2); // Output: true (Same instance) } }

    Explanation:#

    • static ensures that the instance is shared across the application.
    • final ensures that the instance is assigned only once.
    • Private Constructor prevents multiple object creation.

    When to Use Singleton?#

    ✅ Managing configuration settings. 

    ✅ Handling logging frameworks. 

    ✅ Database connection pooling. 

    ❌ Not suitable for general object creation.

    Conclusion#

    In this blog, we learned:

    • What a Singleton Class is and why it is useful.
    • How static and final help in implementing Singleton.
    • A simple example to illustrate Singleton.

    Want to Master Spring Boot and Land Your Dream Job?

    Struggling with coding interviews? Learn Data Structures & Algorithms (DSA) with our expert-led course. Build strong problem-solving skills, write optimized code, and crack top tech interviews with ease

    Learn more

    Last updated on Apr 09, 2025

    Subscribe to our newsletter

    Read articles from Coding Shuttle directly inside your inbox. Subscribe to the newsletter, and don't miss out.