Methods of Java · Introduction to Java Programming

Static Block

Watch lectures

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.
AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.

← All Introduction to Java Programming modules