You are currently viewing Java Initializer Blocks
java_logo

Java Initializer Blocks

Instance initializer blocks play a crucial role in class initialization, providing developers with a powerful tool to execute code when an object is created.

Instance initializer blocks are code blocks within a Java class that are executed when an object of the class is created. They are defined within curly braces {} without any method or constructor declaration. These blocks are particularly useful for performing complex initializations that cannot be achieved in a single line or within a constructor.

Let’s consider a scenario where we want to initialize a list of default values for a class member.

import java.util.ArrayList;
import java.util.List;

public class DefaultsInitializer {
    private List<String> defaultValues;

    {
        // Instance Initializer Block
        defaultValues = new ArrayList<>();
        defaultValues.add("Default 1");
        defaultValues.add("Default 2");
        defaultValues.add("Default 3");
    }

    // Other constructors, methods, and members
}

In this example, the instance initializer block initializes the defaultValues list with predefined default values when an object of the DefaultsInitializer class is created.

Method Blocks vs Initializer Blocks

Instance Initializer Block:
Called automatically when an object is created.
Executes just before the constructor.
Declared using curly braces {} within the class, outside any method or constructor.
Can access and modify both static and instance variables.


Method Block:
Called explicitly by invoking the method.
Executes only when the method is called.
Declared using method declaration syntax with a return type.
Can access and modify only static variables directly. For instance variables, it requires an object reference.