While skimming through amazing Core Java book earlier on today, I re-discovered the initialization blocks theme, that can be used to setup your class data fields.
There are two common ways to initialize class attributes:
- Provide value in declaration, i.e. you set the value as you introduce data field
- Set value in constructor
public class Testy {
private int a = 12; // you set value in declaration
private int b;
private int c;
public Testy()
{
this.b = 21; // you set value in constructor
}
}
However, there’s actually a third way:
- Use initialization block
public class Testy {
private int a = 12; // you set value in declaration
private int b;
private int c;
public Testy()
{
this.b = 21; // you set value in constructor
}
// object initialization block
// executed every time object of the class is constructed
{
this.c = 44;
}
}
What benefit this structure has over other methods? You can use this to abstract common construction logic (when you have several constructors relying on some common initialization). But, the same effect could be achieved by calling common constructor via this() as the first statement to every constructor requiring prior call to common constructor. Overall, I can hardly think about any use case that initialization block could resolve better than using constructors directly. It might be issue of preference.
However, initialization blocks could still be very useful. When? In situations where constructors do not provide a solution: yes I am talking about static fields. If you need some complex logic initializing your static fields, static initialization block resolves the issue neatly:
public class Testy {
protected static int x;
// static initialization block
static // Note the word "static" before initialization block curly braces.
{
Random generator = new Random();
Testy.x = generator.nextInt(100);
}
}
NB:
Initialization blocks are executed before constructors and after fields are initialized to their default values (which are either values provided in field declaration or one of true, 0, null depending on type). Static initialization takes place only once – when class is loade


