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
