In our team we found some strange behaviour where we used both static
and final
qualifiers. This is our test class:
public class Test {
public static final Test me = new Test();
public static final Integer I = 4;
public static final String S = "abc";
public Test() {
System.out.println(I);
System.out.println(S);
}
public static Test getInstance() { return me; }
public static void main(String[] args) {
Test.getInstance();
}
}
When we run the main
method, we get a result of:
null
abc
I would understand if it wrote null
values both times, since the code of static class members is executed from top to bottom.
Can anyone explain why this behaviour is happening?
S
is a compile-time constant, following the rules of JLS 15.28. So any occurrence of S
in the code is replaced with the value which is known at compile-time.
If you change the type of I
to int
, you'll see the same for that, too.
See more on this question at Stackoverflow