Skip to content


Java initializer block

Had a discussion about java initializer blocks with a friend a while back, and thought I’d summarize some of the points here, along with tested code examples.

Static Initializer

public class initializerTest {

    private final static String var1;
    private static String var2;

    static {
        var1 = "test";
        var2 = "a";

        System.out.println("hello");
        initializerTest t = new initializerTest();
    }

    public initializerTest() {
        System.out.println(var1);
        System.out.println(var2);
    }
}

Output:

hello
test
a
test
a
  • Can initialize final variables
  • Can run code
  • Can instantiate classes
  • Initializer blocks run before constructors
The output seen here is produced (in order) by:
  1. Initializer is run when the class definition is loaded, and hello is printed out
  2. Initializer instances a copy of initializerTest, which causes the constructor to print test\n a
  3. The main method that instanced a copy of initializerTest has the object’s constructor called, resulting in another test\n a
Non-static initializer
Of course the same block works without the static keyword, and works as a non-static initializer
Exception handling
Error: Unhandled exception, Initializer does not exit normally
{
    throw new Exception("this is checked");
}
Error: Initializer does not exit normally
{
    throw new RuntimeException("this is unchecked");
}
No errors:
{
    try {
        if (var1.equals("a"))
            throw new Exception("this is checked");
    } catch (Exception e) {
        //do nothing
    }
}
{
    if (var1.equals("a"))
        throw new RuntimeException("this is checked");
}
  • Initializer block must exit normally (no unhandled checked exception)
  • Unchecked exceptions can be thrown

Posted in Java. Tagged with , , .