What is an initialization block?

Sumithra picture Sumithra · Oct 21, 2010 · Viewed 68.4k times · Source

We can put code in a constructor or a method or an initialization block. What is the use of initialization block? Is it necessary that every java program must have it?

Answer

aioobe picture aioobe · Oct 21, 2010

First of all, there are two types of initialization blocks:

  • instance initialization blocks, and
  • static initialization blocks.

This code should illustrate the use of them and in which order they are executed:

public class Test {

    static int staticVariable;
    int nonStaticVariable;        

    // Static initialization block:
    // Runs once (when the class is initialized)
    static {
        System.out.println("Static initalization.");
        staticVariable = 5;
    }

    // Instance initialization block:
    // Runs each time you instantiate an object
    {
        System.out.println("Instance initialization.");
        nonStaticVariable = 7;
    }

    public Test() {
        System.out.println("Constructor.");
    }

    public static void main(String[] args) {
        new Test();
        new Test();
    }
}

Prints:

Static initalization.
Instance initialization.
Constructor.
Instance initialization.
Constructor.

Instance itialization blocks are useful if you want to have some code run regardless of which constructor is used or if you want to do some instance initialization for anonymous classes.