Static Block
1. What Is It? (beginner)
Static block = static { ... } runs once when class loads (before main, before any object!). Setup shared resources: drivers, config, static maps.
2. Order Proof (exam trace favourite!)
class Demo {
static int x;
static { x = 100; System.out.println("static block!"); } // 1st!
{ System.out.println("instance block!"); } // per object!
Demo() { System.out.println("constructor!"); } // after instance!
public static void main(String[] args) {
System.out.println("main! x=" + x);
new Demo(); new Demo();
}
}
// Output: static block! → main! x=100 → instance, constructor → instance, constructor
Order: static block (once) → main → per new: instance block → constructor!
3. Rules
- NO params, NO return, NO
this(no object yet!). - Multiple static blocks run top-to-bottom.
- Exception? Must catch inside (can't throw checked!).
4. Use
static Map<String,Integer> CODES = new HashMap<>();
static { CODES.put("IN", 91); CODES.put("US", 1); } // fill once!
5. Exam Points
- Order trace (static → main → instance → ctor) — 5-7 marks, very frequent.
- Once vs per-object — 3 marks, frequent.