Java initializers

Posted on October 13, 2009

A feature a bit old, introduced in Java 1.1, but, shame on me :P, I've found it only recently, maybe it could get some use in corner case situations.
Let me clarify the point a bit: I've said "corner case situation" and not "wow let's use it everywhere!1!!" because it is not widely known and it is not immediatly understandable, I've made a little survey where I work and mostly nobody ever heard of this possibility. As of now I've used this only once in a test class, I was late on a project and this logger just wasn't logging, I added a comment (almost the same as a //sorry), initialized the logger in the instance initializer and went over. Bad practice? Yes it was. I were late, at the moment I just needed to pass over the problem.
Also have a look at the links at the bottom of the page if you want to know about the initial part of a Java object life cycle.

Following are two test classes, partly taken from stackoverflow, the final goal is to have a general understanding of how initializers work.

public class InitTest {
    private static int testValue;
    public InitTest(int testParameter) {
     System.out.println("constructor called");
        testValue = testParameter;
        System.out.println(testValue + "");

    }

    static {
     System.out.println("static initializer called");
        System.out.println(testValue + "");
    }

    {
     System.out.println("instance initializer called");

        System.out.println(testValue + "");
    }
}

public class Main {
    public static void main(String args[]){
        new InitTest(1);
        new InitTest(2);
    }
}

This is the output that gets printed after executing the main method:

static initializer called
0
instance initializer called
0
constructor called
1
instance initializer called
1
constructor called
2

These could be useful int the following examples:

  • when you create an anonimous inner class you do not have a constructor, then by using an instance initializer you solve the problem
  • instance initializers are useful when you have code that has to be shared among constructors
  • ArrayList numbers = new ArrayList() {{ add("1"); add("2"); add("3"); }};
  • when a method is called statically a static initializer gets called before so one can put there initialization code

On the argument:

Browse the archive

blog comments powered by Disqus