I came across this bug in our code today and it took a while to figure. I found it interesting so I decided to share it. Here is a simplified version of the problem:
public class Test {
static
{
text = "Hello";
}
public static String getTest() {
return text + " World";
}
private static String text = null;
}
Guess what Test.getTest(); returns & why?
It should print “null world”. Static initializations are done in the order listed. If you move the declaration higher than the static block you should get “Hello World”.