Course contentsShow
← Java
Lesson 353 of 2,8708. Classes and EncapsulationFree lesson

Multiple Instance Initializers and Execution Order

Understand that multiple initializer blocks execute in the order they appear in the class definition.

Multiple Instance Initializers and Execution Order

What you'll learn: You'll discover how Java handles multiple instance initializer blocks when they appear in the same class and the precise order in which they execute.

The Core Idea

When a class contains multiple instance initializer blocks, Java executes them in the exact order they appear in your source code, from top to bottom. Each block runs in sequence before the constructor body executes.

Think of it like following a recipe where preparation steps must happen in order: first chop the vegetables, then heat the pan, then add oil. If you rearrange the steps, you get different results. Similarly, if you place initializer blocks in a different order, they execute in that new order.

How It Works

public class Example {
    private int first;
    private int second;
    
    // First initializer block - runs FIRST
    {
        first = 10;
        System.out.println("First block executed");
    }
    
    // Second initializer block - runs SECOND
    {
        second = 20;
        System.out.println("Second block executed");
    }
    
    // Constructor - runs THIRD
    public Example() {
        System.out.println("Constructor executed");
    }
}

When you create an Example object:

First block executed
Second block executed
Constructor executed

The execution order is always:

  1. Field initializations (from declaration)
  2. Instance initializer blocks (top to bottom)
  3. Constructor body

Why Multiple Blocks?

While you rarely need multiple blocks, they can organize complex initialization logic into logical sections, especially when different blocks handle different responsibilities or validate different aspects of object state.

Key Takeaway: Multiple instance initializer blocks execute sequentially in the order they're written in the class, always before the constructor body runs.