Sobes.tech
Junior

What is an initialization block in Java?

sobes.tech AI

Answer from AI

Initialization block in Java is a block of code that executes when an object is created. There are two types:

  1. Static initialization block:
    • Declared with the keyword static {}.
    • Executes once when the class is loaded into JVM memory, before any objects of this class are created.
    • Used for initializing static variables or performing other static operations.
    // Static initialization block
    static {
        System.out.println("Static initializer block executed");
        staticVariable = 100;
    }
    
  2. Non-static (instance) initialization block:
    • Declared without the static {} keyword.
    • Executes every time a new instance of the class is created, after memory allocation but before the constructor is called.
    • Used for initializing instance variables or performing operations specific to each object.
    // Non-static initialization block
    {
        System.out.println("Instance initializer block executed");
        instanceVariable = 10;
    }
    

Execution order:

  1. Static initialization blocks (in the order of their declaration).
  2. Non-static initialization blocks (in the order of their declaration).
  3. Constructors.

Example:

class Example {
    static int staticVariable;
    int instanceVariable;

    static {
        System.out.println("Static block 1");
        staticVariable = 1;
    }

    {
        System.out.println("Instance block 1");
        instanceVariable = 11;
    }

    static {
        System.out.println("Static block 2");
        staticVariable = 2;
    }

    {
        System.out.println("Instance block 2");
        instanceVariable = 22;
    }

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

    public static void main(String[] args) {
        System.out.println("Creating object 1");
        new Example();
        System.out.println("Creating object 2");
        new Example();
    }
}

Output:

Static block 1
Static block 2
Creating object 1
Instance block 1
Instance block 2
Constructor
Creating object 2
Instance block 1
Instance block 2
Constructor

Main uses:

  • Static blocks: Initialization of static fields, resource loading at class startup.
  • Non-static blocks: Performing common initialization logic before any constructor (e.g., setting default values that can be changed in constructors).