Sobes.tech
Junior

Why are static blocks used in Java?

sobes.tech AI

Answer from AI

Static initialization blocks are used for:

  • Initializing static fields of a class with complex logic that cannot be performed at the point of declaration.
  • Performing one-time actions when the class is loaded into the JVM for the first time.

They are executed in the order they appear in the code, immediately after the class is loaded, but before any instances are created and before static methods are called.

class MyClass {
    static final String GREETING;
    static {
        // Complex initialization logic
        String prefix = "Hello";
        String suffix = "World";
        GREETING = prefix + " " + suffix;
        System.out.println("Static initialization block executed.");
    }

    public static void main(String[] args) {
        System.out.println(MyClass.GREETING);
    }
}