Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I recently came across a Java construct I have never seen before and was wondering whether I should use it. It seems to be called initializer blocks.

public class Test {
  public Test() { /* first constructor */ }
  public Test(String s) { /* second constructor */ }
  {
    doStuff();
  }
}

The code block will be copied into each constructor, i.e. if you have multiple constructor you do not have to rewrite code.

However, I see three main drawbacks using this syntax:

  1. It is one of the very few cases in Java where the order of your code is important, as you can define multiple code blocks and they will be executed in the order they are written. This seems harmful to me as simply changing the order of code blocks will actually change the code.
  2. I do not really see any benefits by using it. In most cases, the constructors will call each other with some pre-defined values. Even if this is not the case, the code could simply be put into a private method and called from each constructor.
  3. It reduces readability, as you could put the block at the end of the class and the constructor is normally at the beginning of the class. It is quite counter-intuitive to look at a completely different part of a code file if you do not expect that to be necessary.

If my above statements are true, why (and when) was this language construct introduced? Are there any legitimate use cases?

share|improve this question
1  
The example you've posted doesn't include anything that looks like an initializer block. –  Simon B May 12 at 15:01
2  
@SimonBarker look again – the { doStuff(); } on the class level is an initializer block. –  amon May 12 at 15:03
    
@SimonBarker The code block that is surrounding doStuff() –  dirkk May 12 at 15:03
1  
ayp-sd.blogspot.de/2012/12/… –  gnat May 12 at 15:13
    
@gnat Thanks, that's a helpful link in explaining a legitimate use case. Also, now I finally made the connection between the double braces and initializer blocks - I always assumed double braces is simply a language construct. –  dirkk May 12 at 15:22

2 Answers 2

There are two cases where I use initializer blocks.

The first one is for initializing final members. In Java, you can initialize a final member either inline with the declaration, or you can initialize it in the constructor. In a method, it is forbidden to assign to a final member.

This is valid:

final int val = 2;

This is valid too:

final int val;

MyClass() {
    val = 2;
}

This is invalid:

final int val;

MyClass() {
    init();
}

void init() {
    val = 2;
}

If you have multiple constructors, and if you can't initialize a final member inline (because the initialization logic is too complex), or if the constructors cannot call themselves, then you can either copy/paste the initialization code, or you can use an initializer block.

final int val;
final int squareVal;

MyClass(int v, String s) {
    this.val = v;
    this.s = s;
}

MyClass(Point p, long id) {
    this.val = p.x;
    this.id = id;
}

{
    squareVal = val * val;
}

The other use case I have for initializer blocks is for building small helper data structures. I declare a member, and put values in it right after its declarations in its own initializer block.

private Map<String, String> days = new HashMap<String, String>();
{
    days.put("mon", "monday");
    days.put("tue", "tuesday");
    days.put("wed", "wednesday");
    days.put("thu", "thursday");
    days.put("fri", "friday");
    days.put("sat", "saturday");
    days.put("sun", "sunday");
}
share|improve this answer

In addition to the initialization of an instance variable that is declared as final (see barjak's answer), I would also mention static initialization block.

You can use them as kind of "static contructor".

That way you can do complex initializations on a static variable a the first time the class is referenced.

Here is an example inspired by barjak's one:

public class dayHelper(){
    private static Map<String, String> days = new HashMap<String, String>();
    static {
        days.put("mon", "monday");
        days.put("tue", "tuesday");
        days.put("wed", "wednesday");
        days.put("thu", "thursday");
        days.put("fri", "friday");
        days.put("sat", "saturday");
        days.put("sun", "sunday");
    }
    public static String getLongName(String shortName){
         return days.get(shortName);
    }
}
share|improve this answer
    
@FrustratedWithFormsDesigner I never meant it was equivalent, that is why I wrote a distinct answer. –  C.Champagne May 12 at 18:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.