Advertisement
Intermediate Java, Java Fundamentals: Syntax, Data Types & Operators

What is the difference between an instance initializer block and a static initializer block, and when does each execute relative to a class's constructors?

Short answer

A static initializer block (static { ... }) runs exactly once, when the class is first loaded/initialized by the JVM, before any instance of the class is ever created, used for one-time setup of static state; an instance initializer block ({ ...

Save Java mock interview
Advertisement
AModel answer
A static initializer block (static { ... }) runs exactly once, when the class is first loaded/initialized by the JVM, before any instance of the class is ever created, used for one-time setup of static state; an instance initializer block ({ ... }, without the static keyword, at the class body level) runs every single time a NEW instance is created, immediately before the constructor's own body executes (but after any explicit or implicit super() call), commonly used for shared initialization logic needed across multiple overloaded constructors, avoiding the need to duplicate that logic in each constructor individually.
public class Example {
    static { System.out.println("Static block: runs ONCE, at class loading"); }
    { System.out.println("Instance block: runs EVERY time a new instance is created"); }

    public Example() { System.out.println("Constructor"); }
    public Example(int x) { System.out.println("Constructor with arg"); }
}

new Example();      // prints: Static block, Instance block, Constructor
new Example(5);      // prints: Instance block, Constructor with arg -- static block does NOT run again
Real-world example
A class with multiple overloaded constructors that all need to perform identical shared setup logic (like initializing a shared collection field) uses an instance initializer block to consolidate that logic in one place, avoiding duplicating identical setup code across each individual constructor overload.
Likely follow-ups
  • What is the guaranteed execution order when a class has multiple static or instance initializer blocks declared at different points in the class body?
  • How does an instance initializer block's execution timing relate to field initializers declared inline at the point of field declaration?
Related topics