liveBook · Manning

Class initialization

As explained in 100 Java Mistakes and How to Avoid Them

Class initialization is the JVM process that initializes a class's static fields and static initialization blocks before the class is first actively used.

Class initialization runs a class’s static field initializers and static blocks once, before the class is used. Declaration order normally controls field initialization, so an earlier field cannot safely depend on a later one. section 3.9.3

A static field used too early

In Version, CURRENT calls parse() before the later REGEX field has been initialized. parse() therefore calls matcher on null, causing class initialization to fail with NullPointerException. Move REGEX before CURRENT, or remove the ordering dependency. section 3.9.1

Cross-class dependencies make the result depend on which class starts first. If A initializes B while B reads A.WELCOME, B may capture null; launching B first can instead produce HELLO. Even an apparently unused static field can trigger this behavior. section 3.9.3

Avoid and investigate initialization-order failures:

  • Declare dependent static fields in a safe order and keep static initialization dependencies simple. section 3.9.1
  • Do not rely on logging from a constructor when the logger itself is initialized later; an original construction failure can be masked by NullPointerException. section 3.9.1
  • Use IntelliJ IDEA for simple nullability warnings and PVS-Studio for more advanced initialization-cycle analysis; inspect the order rather than dismissing a warning automatically. section 3.9.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Descends from once-only JVM execution to declaration order, cross-class cycles, concurrency symptoms, and analyzer guidance.
Examples
Uses Version parsing, mutually dependent classes A and B, singleton logging, parallel initialization, and thread-dump monitor states.
What it assumes
Assumes Java familiarity while establishing how static fields, static blocks, and class initialization interact.
What you can do after
Diagnose initialization-order failures, prevent unsafe static dependencies, and interpret analyzer warnings or thread-dump monitor waits.
How it connects
Ties static fields, static initialization blocks, class initialization order, circular dependencies, singleton construction, and static analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.