Java Initialization Blocks: Learn Instance Initialization with Examples

0

Constructors are not the only place where Java can perform object initialization. A class can also contain an initialization block, a special block of code that executes automatically when an object is created.

Initialization blocks are useful when several constructors need to perform the same setup work. Instead of repeating that code inside every constructor, you can place the common logic inside an instance initialization block.

What Is an Initialization Block?

An initialization block is a block of code written directly inside a class but outside methods and constructors. Java executes an instance initialization block whenever an object is created.

class Student {

    {
        System.out.println("Initialization Block");
    }

    Student() {
        System.out.println("Constructor");
    }

}

When an object of Student is created, the initialization block executes before the constructor.

Student student = new Student();
Initialization Block
Constructor

Why Do Initialization Blocks Exist?

Suppose a class has several constructors and every constructor needs the same piece of initialization logic. Copying that logic into every constructor creates duplication.

class Employee {

    String department;

    Employee() {
        department = "Development";
        System.out.println("Employee Created");
    }

    Employee(String name) {
        department = "Development";
        System.out.println("Employee Created");
    }

}

The assignment to department is repeated. An instance initialization block can centralize common initialization.

class Employee {

    String department;

    {
        department = "Development";
    }

    Employee() {
        System.out.println("Employee Created");
    }

    Employee(String name) {
        System.out.println("Employee Created");
    }

}

Now both constructors automatically receive the initialization performed by the block.

Basic Syntax

class ClassName {

    {
        // instance initialization code
    }

}

Notice that there is no method name, constructor name, or special keyword before the braces. The location of the block inside the class tells Java that it is an instance initialization block.

Instance Initialization Block

The block shown above is specifically called an instance initialization block. It belongs to each object rather than to the class as a whole.

class Car {

    {
        System.out.println("Object is being initialized");
    }

}

Every time a new Car object is created, the block executes.

Car car1 = new Car();
Car car2 = new Car();
Car car3 = new Car();
Object is being initialized
Object is being initialized
Object is being initialized

The block runs once for each object. It is not executed only once when the class is loaded.

Initialization Block and Constructors

One of the most important rules is that instance initialization blocks execute before the constructor body for an object.

class Student {

    {
        System.out.println("Initialization Block");
    }

    Student() {
        System.out.println("Constructor");
    }

}

The output is:

Initialization Block
Constructor

This happens because Java performs instance initialization before entering the constructor body.

Initialization Block with Instance Variables

An instance initialization block can initialize instance variables directly.

class Account {

    String type;
    double balance;

    {
        type = "Savings";
        balance = 1000.0;
    }

    Account() {
        System.out.println("Account Created");
    }

}

When the object is created, the instance variables are initialized before the constructor body executes.

Account account = new Account();

System.out.println(account.type);
System.out.println(account.balance);
Account Created
Savings
1000.0

The constructor runs after the initialization block, so by the time the constructor body executes, the instance variables have already received the values assigned by the block.

Multiple Initialization Blocks

A class can contain more than one instance initialization block. When that happens, Java executes them in the order in which they appear in the source code.

class Demo {

    {
        System.out.println("Block 1");
    }

    {
        System.out.println("Block 2");
    }

    Demo() {
        System.out.println("Constructor");
    }

}
Block 1
Block 2
Constructor

The source-code order matters. Java does not randomly execute initialization blocks.

Initialization Blocks and Constructors with Parameters

An instance initialization block runs regardless of which constructor is selected.

class Employee {

    {
        System.out.println("Common Initialization");
    }

    Employee() {
        System.out.println("No-Argument Constructor");
    }

    Employee(String name) {
        System.out.println("Parameterized Constructor");
    }

}

Creating objects through both constructors demonstrates the behavior.

Employee e1 = new Employee();
Employee e2 = new Employee("Anita");
Common Initialization
No-Argument Constructor
Common Initialization
Parameterized Constructor

The block is shared by every instance creation path, which makes it useful for truly common initialization logic.

Initialization Order Inside a Class

To understand initialization blocks properly, you need to know that Java does not simply jump directly into the constructor. Instance fields, instance initialization blocks, and the constructor participate in an ordered initialization process.

class Demo {

    int number = 10;

    {
        System.out.println("Initialization Block");
    }

    Demo() {
        System.out.println("Constructor");
    }

}

For an object of this class, the instance field initializer and initialization block execute before the constructor body.

Demo demo = new Demo();
Initialization Block
Constructor

The field initializer itself does not print anything here, but its assignment occurs before the initialization block.

Field Initializers and Initialization Blocks

Instance variable initialization and initialization blocks are both part of instance initialization. Their execution follows the order in which they appear in the class.

class Demo {

    int number = 10;

    {
        number = 20;
        System.out.println(number);
    }

    Demo() {
        System.out.println(number);
    }

}
20
20

The field initially receives 10, then the initialization block changes it to 20, and finally the constructor sees the updated value.

Order Matters

Consider moving the initialization block before the field initializer.

class Demo {

    {
        number = 20;
    }

    int number = 10;

    Demo() {
        System.out.println(number);
    }

}

This arrangement leads to a compile-time problem because the instance variable is referenced from the initialization block before its declaration is in a usable state for that context. The safest rule for beginners is to understand initialization according to source order and avoid forward references that make object initialization difficult to reason about.

Initialization Block vs Constructor

Initialization Block Constructor
Written directly inside the class Has the same name as the class
Has no name Has a constructor name
Runs automatically during object initialization Runs automatically during object creation
Common logic can be shared across constructors Can receive parameters
Cannot be called directly Selected through object creation and constructor matching

Initialization Block vs Static Block

Do not confuse an instance initialization block with a static initialization block. The presence of the static keyword changes the behavior completely.

Instance Initialization Block Static Initialization Block
Written as { } Written as static { }
Runs when an object is created Runs when the class is initialized
Runs once per object Normally runs once for the class initialization
Can directly work with instance state Primarily used for static state

The next chapter will examine static blocks in detail.

When Should You Use Initialization Blocks?

Initialization blocks are valid Java, but they are not something you should automatically use for every initialization task. In modern application code, constructors and field initializers are often clearer choices.

An initialization block can make sense when several constructors share genuinely common initialization behavior and constructor chaining does not provide a cleaner design.

  • Use field initializers for simple constant-like instance initialization.
  • Use constructors when initialization depends on constructor parameters.
  • Use initialization blocks when common instance setup must run before every constructor body.
  • Avoid large initialization blocks that hide important business logic.

Common Beginner Mistakes

Thinking the Block Runs Only Once

An instance initialization block runs for every object created, not just once for the class.

Putting the Block Inside a Method

class Demo {

    void display() {

        {
            System.out.println("Hello");
        }

    }

}

The inner braces in this example are simply a local block inside a method, not an instance initialization block. An initialization block must be directly inside the class body.

Expecting It to Run After the Constructor

Instance initialization occurs before the constructor body. Therefore, the initialization block does not execute after the constructor.

Using It for Everything

Initialization blocks are a specialized feature. If a simple field initializer or constructor communicates the intent more clearly, prefer the simpler approach.

Important: Good Java code is not about using every language feature available. Use initialization blocks when they make shared instance initialization clearer; otherwise, prefer the simplest readable design.

Interview Insight

A common interview question is: When does an instance initialization block execute? It executes during instance initialization, before the constructor body, whenever an object is created.

Another common question is: If a class has multiple initialization blocks, which one runs first? The blocks execute in their textual order, from top to bottom, as part of instance initialization.

Quick Revision

Concept Key Point
Initialization Block Code block directly inside a class
Type Instance initialization block
Execution Runs during object initialization
Constructor Order Runs before the constructor body
Multiple Blocks Execute in source-code order
Frequency Runs once for each object
Main Use Share common instance initialization logic

Final Thoughts

Initialization blocks give Java another way to organize instance setup, especially when several constructors need the same common initialization. The key idea is simple: an instance initialization block belongs to the object, executes before the constructor body, and runs every time a new object is created. Use it thoughtfully, because readable constructors and field initializers are often preferable when they express the intent more directly.

Post a Comment

0Comments
Post a Comment (0)