Initialization blocks in Java
I discovered yesterday a feature of the Java language that I didn't know of: initialization blocks. This is something that we rarely see in code, hence you may not be aware of their existence too...
You probably already know of static initialization blocks such as:
public class Foo { public static final int MY_INT; static { MY_INT = 1; } }
In this example, the static block is called when the Foo class is loaded by a classloader. It can perform anything you want of course, but its main purpose is to eventually initialize / configure static class fields.
What I didn't know is that you can have such blocks at the class instance level as well:
public class Bar { private int myInt; { myInt = 1; } }
Here this block is called before the Bar class constructors. It can do anything including touching instance fields.
I must confess that I can hardly see a use-case for this lesser-known feature of the Java language since one is more likely to use a constructor for such tasks.
It may be sometimes nicer to read with anonymous classes though:
MyListener listener = new MyListener() { { bind("this").with("that"); // etc } };
What do you think? Have you ever seen a great application of those blocks? I'm really curious!
Related posts:
- Playing with Berkeley DB Java Edition and Guice
- The Java 6 VM must be magic
- IzPack and Java Web Start
- Java: flashback in time
- lzma-java version 1.0


March 26th, 2009 - 01:20
I use them often for clarity. I think that this code
class Foo {
private final Map numbers = new HashMap();
{
numbers.put( “one”, 1 );
numbers.put( “two”, 2 );
numbers.put( “three”, 3 );
}
private final List days = new ArrayList( 7 );
{
days.put( “Sunday” );
days.put( “Monday” );
days.put( “Tuesday” );
days.put( “Wednesday” );
days.put( “Thursday” );
days.put( “Friday” );
days.put ( “Saturday” );
}
}
is more readable than a cluttered constructor like that:
class Foo {
private final Map numbers = new HashMap();
private final List days = new ArrayList();
public Example() {
numbers.put( “one”, 1 );
numbers.put( “two”, 2 );
numbers.put( “three”, 3 );
days.put( “Sunday” );
days.put( “Monday” );
days.put( “Tuesday” );
days.put( “Wednesday” );
days.put( “Thursday” );
days.put( “Friday” );
days.put ( “Saturday” );
}
}
This is also an elegant way to share common initialization code between multiple constructors when they cannot call each other.
Apart this, and for anonymous classes initialization like in your example, I do not see any other added value.
Using initialization blocks, is exactly the same thing than putting the corresponding code at the begining of the constructor (the compiler generates a copy of corresponding bytecode at this place).
March 26th, 2009 - 11:31
Thanks Laurent.