Tuesday, December 20, 2011

Are static fields initialized before constructor is called?

I've encountered this while debugging one very strange issue in third party library. Decompiled code made this case even more interesting and not so obvious.

How do you think, what is the output for following program?

public class AreStaticFieldsInitializedBeforeConstructorIsCalled {
public static void main(String[] args) {
new A();
}
}
class A {
static A a = new A();
static String staticField = "1";
static final String CONSTANT = "2";
public A() {
System.out.println(staticField);
System.out.println(CONSTANT);
}
}


Output is:

null
2
1
2

Constructor is called before "staticField" is initialized.