library
intermediateInitialization Blocks: Static & Instance
Understand the order of execution of static blocks, instance blocks, constructors, and field initializers.
Java has two types of initialization blocks that run automatically:
Static block = setting up the factory before any product is made (happens once). Instance block = quality check on the assembly line (happens for every product before it ships).
Key Concepts
1
Static initialization blocks run once when the class is loaded, before any instance is created. They execute in declaration order and are used for complex static field setup (loading native libraries, populating static maps, reading config).
2
Instance initialization blocks run every time an instance is created, before the constructor body. They're copied by the compiler into every constructor after the super() call. Used when multiple constructors share initialization logic that can't go in a common this() chain.
3
Full initialization order:
1. Static fields and static blocks (top to bottom, once per class load)
2. Parent class static init (if not already done)
3. Parent instance fields and instance blocks
4. Parent constructor body
5. Child instance fields and instance blocks
6. Child constructor body
4
This order matters in interviews. A classic question: what prints when you create a new Child()?
5
Instance blocks are rarely used in practice — constructor chaining with this() is cleaner. But they're essential for anonymous classes (which can't have named constructors) and double-brace initialization (an anti-pattern that creates anonymous inner classes).