Video in progress

Strong Junior ⚙️ JVM and memory

What does this code print? Explain when a class gets initialized.

class A {
    static final String VERSION = "1.0";
    static { System.out.println("A init"); }
}
class B {
    static int count = 5;
    static { System.out.println("B init"); }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(A.VERSION);
        System.out.println(B.count);
    }
}

Only main and B run: A.VERSION is a compile-time constant, so A is not initialized at all, while B.count is an ordinary static field and touching it runs B's static block.

📖 Answer

The output:

1.0
B init
5

"A init" is not printed. The reason: a static final field whose value is a literal is a compile-time constant. The compiler writes "1.0" straight into the bytecode of the Main class, so at runtime A is never touched.

The JVM initializes classes lazily. Static blocks and static fields run the first time one of these happens:

  • new A();
  • a static method is called;
  • a non-constant static field is read or written;
  • reflection (Class.forName("A")) or initialization of a subclass.

Loading and initialization are two different steps. Writing A.class may load the class, but it does not run the static block.

A practical trap: you change a constant in one module but don't recompile the module that uses it, and the old value stays baked into it.