What is a static block in Java?

A static block is a special block of code in Java that is executed only once when the class is loaded into memory by the JVM. It is primarily used to initialize static variables or perform one-time setup operations before any object is created or any static method is called.

Key Points

Example

Suppose an application needs to initialize a static database URL before any object is created. A static block can perform this initialization.

class Demo {

    static String message;

    static {

        message = "Static Block Executed";

        System.out.println(message);
    }

    public static void main(String[] args) {

        System.out.println("Main Method Executed");
    }
}

Output

Static Block Executed

Main Method Executed

Execution Order Example

class Demo {

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

    Demo() {
        System.out.println("Constructor");
    }

    public static void main(String[] args) {

        System.out.println("Main Method");

        new Demo();
    }
}

Output

Static Block

Main Method

Constructor

Multiple Static Blocks

class Demo {

    static {
        System.out.println("Static Block 1");
    }

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

    public static void main(String[] args) {
    }
}

Output

Static Block 1
Static Block 2

Common Use Cases

Important Notes

Interview Tip

A concise interview answer is

A static block is a special initialization block that executes once when a class is loaded into memory. It is mainly used to initialize static variables and perform one-time setup tasks before any object creation or method execution.

Last updated: 11 November 2026

Previous question: Is it possible to access non-static members from within a static method?

Next question: Can we print something to the console without a main method in Java?

More Core Java - Level II interview questions

All Core Java - Level II questions