Java Class Static Blocks
How and Why They Are Used

What is a Static Block in Java?

In Java, a static block (also known as a static initialization block) is a code block that's executed once when the class is loaded into memory. It's mostly used to initialize static variables or execute code that must run before any objects of the class are created.

Why Use a Static Block?

Static blocks are especially useful when:

  • You need to perform complex static variable initialization.
  • You want to run code at class loading time – like reading configuration or logging setup.
  • You want something to execute even before the main method is called.

Syntax of a Static Block

class MyClass {
    static {
        // This code runs once when the class is loaded
    }
}

Example 1: Basic Static Block Execution

public class StaticBlockExample {
    static {
        System.out.println("Static block executed");
    }

    public static void main(String[] args) {
        System.out.println("Main method executed");
    }
}
Static block executed
Main method executed

Explanation:

When you run the class, the JVM loads it and executes the static block first. After that, it invokes the main() method.

Example 2: Initializing Static Variables

public class Config {
    static int MAX_USERS;
    static String APP_NAME;

    static {
        MAX_USERS = 100;
        APP_NAME = "MyApp";
        System.out.println("Static block: Configuration loaded");
    }

    public static void main(String[] args) {
        System.out.println("App: " + APP_NAME);
        System.out.println("Max users: " + MAX_USERS);
    }
}
Static block: Configuration loaded
App: MyApp
Max users: 100

Explanation:

The static block sets up configuration data for the class. It's run only once and the values are available for use throughout the application wherever static members are accessible.

Example 3: Multiple Static Blocks

public class MultiStaticBlocks {
    static {
        System.out.println("Static block 1");
    }

    static {
        System.out.println("Static block 2");
    }

    public static void main(String[] args) {
        System.out.println("Main method");
    }
}
Static block 1