Why java Instance initializers? [duplicate]

What is the sense of "Instance Initializers" in Java ?
Can't we just put that block of code at the beginning of the constructor instead?


I use them very often, typically for creating and populating Map in one statement (rather than using an ugly static block):

private static final Map<String, String> CODES = new HashMap<String, String>() {
    {
        put("A", "Alpha");
        put("B", "Bravo");
    }
};

One interesting and useful embellishment to this is creating an unmodifiable map in one statement:

private static final Map<String, String> CODES = 
    Collections.unmodifiableMap(new HashMap<String, String>() {
    {
        put("A", "Alpha");
        put("B", "Bravo");
    }
});

Way neater than using static blocks and dealing with singular assignments to final etc.

And another tip: don't be afraid to create methods too that simplify your instance block:

private static final Map<String, String> CODES = new HashMap<String, String>() {
    {
        put("Alpha");
        put("Bravo");
    }

    void put(String code) {
        put(code.substring(0, 1), code);
    }
};

You could indeed put the code at the beginning of every constructor. However, that's precisely the point of an instance initializer: its code is applied to all constructors, which can be handy if you have many constructors and a bit of code that is common to all of them.

(If you're just starting out with programming, you might not have known that it is possible to create many constructors for the same class (as long as they take different parameters); this is known as constructor overloading. If you only have one constructor, then an instance initializer is indeed not very useful (Edit: Unless you abuse it in creative fashions, as illustrated in the other answers).)