Memra

Initialization order: static, instance, and constructor

The precise order Java initialises a class — and how to trace it on exam questions.

When does each piece of code run?

Java guarantees a specific initialisation order that the OCP exam tests directly:

  1. Static fields and static initialiser blocks — run once, when the class is first loaded by the JVM, in textual order.
  2. Instance fields and instance initialiser blocks — run on every new, in textual order, *before* the constructor body.
  3. Constructor body — runs last.
public class Sequence {
    static int classCount;
    static { classCount = 1; System.out.println("static block"); }

    int id = ++classCount;
    { System.out.println("instance block"); }

    Sequence() { System.out.println("constructor"); }
}

new Sequence();
new Sequence();

Output:

static block
instance block
constructor
instance block
constructor

The static block fires once at class load. On each new: instance block, then constructor — never the static block again.

NORMAL ~/memra/learn/java-from-zero/initialization-order utf-8 LF