static finite elements are initialized before other static members.
non-finite static elements are initialized in order of appearance
Therefore, in your first case:
static Test t=new Test(); static int a=5;
The constructor is first called before a initialized, so a=0 displayed.
In the second case, static final a initialized to t , so a=5 displayed when the first instance of Test . When a not static, it is initialized before the constructor runs, so a=5 displayed again.
Regarding editing in your question.
In section 12.4.2 of the JLS :
- Then initialize the final class variables and interface fields whose values are constant compilation time constant (§8.3.2.1, §9.3.1, §13.4.9, §15.28).
...
- Next, execute either the class variable initializers, or the static class initializers, or interface field initializers, in textual order, as if they were a single block.
You see that class final variables (i.e. static final) are initialized before the rest of the static variables only if their values constitute compilation time constant expressions . 5 is a constant expression. new Test() not. Therefore, a initialized to t , even if both are static.
Eran
source share