23. When should we use static block?

When should we use static block?

  • A class can have multiple static blocks
  • We can use the static block to initialize the value for static member in a class. Static block always execute one time at the class loading time and before the main method is execute.

    Example:

    public class StaticBlockExample {
    // Static member variables
    private static int staticInt;
    private static double staticDouble;
    private static String staticString;

    // Static block for initialization
    static {
    System.out.println(“Static block is executed.”);

    // Initialize the static member variables
    staticInt = 100;
    staticDouble = 99.99;
    staticString = “Hello, World!”;
    }

    // Static methods to get the values of the static member variables
    public static int getStaticInt() {
    return staticInt;
    }

    public static double getStaticDouble() {
    return staticDouble;
    }

    public static String getStaticString() {
    return staticString;
    }

    public static void main(String[] args) {
    // Print the values of the static member variables
    System.out.println(“Static integer: ” + getStaticInt());
    System.out.println(“Static double: ” + getStaticDouble());
    System.out.println(“Static string: ” + getStaticString());
    }
    }

  • We also can use static block for building singleton pattern or read the configuration file.

    Example
    public class Singleton {
    // The single instance of the class
    private static Singleton instance;

    // Static block for initialization
    static {
    try {
    // Simulate some complex initialization
    System.out.println(“Static block is executed for Singleton.”);
    instance = new Singleton();
    } catch (Exception e) {
    throw new RuntimeException(“Exception occurred during Singleton creation”, e);
    }
    }

    // Private constructor to prevent instantiation
    private Singleton() {
    // Private constructor
    }

    // Method to get the single instance of the class
    public static Singleton getInstance() {
    return instance;
    }

    // Example method
    public void showMessage() {
    System.out.println(“Hello World from Singleton!”);
    }

    public static void main(String[] args) {
    // Get the Singleton instance and call its method
    Singleton singleton = Singleton.getInstance();
    singleton.showMessage();
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *