Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Static initializer block

A static { ... } block executes statements during class initialization, not whenever an object is created. Use it to prepare static fields when initialization needs several statements.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

static {
    // initialization statements
}

A static initializer block is a static { ... } block declared in a class body. It is neither a method nor a constructor, and you do not call it directly. It runs during class initialization, not whenever an object is created.

During class initialization, static fields that are constant variables are initialized before the remaining static field initializers and static blocks execute. Those remaining initializers and blocks execute in source order. Class initialization is distinct from loading: triggers include creating an instance or invoking a static method declared by that class. Reading a compile-time constant does not itself trigger initialization. After successful initialization of a particular class, its blocks do not run again.

The block establishes a static context: there is no current object, so you cannot use this, super, or unqualified references to instance fields and methods. A return statement is forbidden; the block must be able to complete normally. Reads of fields declared later are subject to forward-reference restrictions.

In the example, value first receives 3, and the block changes it to 6 before main executes. The two new Main() expressions do not run the block again. By contrast, a plain { ... } block in a class body, without static, is an instance initializer.

Examples

public class Main {
    static int value = 3;

    static {
        value *= 2;
        System.out.println("init: " + value);
    }

    public static void main(String[] args) {
        System.out.println("main: " + value);
        new Main();
        new Main();
    }
}

Result

init: 6
main: 6

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources