Core Java: Static initializer blocks run once, in declaration order, at class load

Static initializer blocks execute a single time when the class is first loaded, in the order they appear, before any static member is used from outside.

Code
class Config {
    static int a;
    static int b;
    static {
        a = 10;
        System.out.println("static block 1, a=" + a);
    }
    static {
        b = a * 2;
        System.out.println("static block 2, b=" + b);
    }
}
System.out.println("Config.a=" + Config.a + ", Config.b=" + Config.b);
Output
static block 1, a=10
static block 2, b=20
Config.a=10, Config.b=20
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms