Platformhard5-8 years

Given a subclass `B extends A`, both with static initializer blocks that print, and a program that never mentions `B` until the very last line where it reads `B.name` — why does `A`'s static initializer definitely run before `B`'s, and why does neither run at program start?

Because Java loads and initializes classes lazily, on first active use — a class just sits on disk as bytecode, completely unnoticed, until something actually needs it — and B isn't touched by anything until the very last line reads B.name, so neither A nor B runs its static block any earlier than that. And once that trigger fires, A is guaranteed to finish initializing first, always, even though nothing in the code explicitly asks for A — because a subclass can never be left in a state where it exists but its inherited (superclass) part doesn't. The JVM initializes the whole inheritance chain outward-in: Object, then every superclass down to the one actually being touched, before that class's own static block runs.

The lesson behind it →
More on Platform