public class InstanceInitialization {
private int i = assign();
private final int j = 5;
private int assign() {
return j;
}
public static void main(String[] args) {
System.out.println(new InstanceInitialization().i);
}
}
The result is 5.
I'm aware of the class initialization and the final static field with the constant value will be initialized first according to JLS
Very strangely, I found the method actually putfield into j with 5 after the invocation of assign() method. This is the decompiled instructions:
private int i;
private final int j = 5 (java.lang.Integer);
public InstanceInitialization() { // <init> //()V
<localVar:index=0 , name=this , desc=Ljvm/classload/InstanceInitialization;, sig=null, start=L1, end=L2>
L1 {
aload0 // reference to self
invokespecial java/lang/Object <init>(()V);
}
L3 {
aload0 // reference to self
aload0 // reference to self
invokespecial jvm/classload/InstanceInitialization assign(()I);
putfield jvm/classload/InstanceInitialization.i:int
}
L4 {
aload0 // reference to self
iconst_5
putfield jvm/classload/InstanceInitialization.j:int
return
}
L2 {
}
}
private assign() { //()I
<localVar:index=0 , name=this , desc=Ljvm/classload/InstanceInitialization;, sig=null, start=L1, end=L2>
L1 {
iconst_5
ireturn
}
L2 {
}
}
From the above code, for the final instance field with the constance value it seems to have the same behaviour, but I failed to find the explanations from JLS.