0
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.

Chao
  • 865
  • 8
  • 21
  • Do you mean the instance field? Instance field initializers (and initialization blocks) are copied into the class constructor. And every class has a constructor, in your case it's the default constructor - and the initialization is invoked there. – Elliott Frisch Nov 18 '15 at 01:30
  • As the linked post explains, the use of `j` is replaced with the constant expression value of `j`. – Sotirios Delimanolis Nov 18 '15 at 01:31
  • I mean why the result isn't 0. If the final j isn't initalized first and before the , the result should be 0. If that, please give me a reference from JLS. – Chao Nov 18 '15 at 01:38
  • Got it. Actually, the final instance field is still intialized in the order of textual occurrence. In the above code, iconst_5 is used in the assign() method instead of reading the value of j. Closed this question. – Chao Nov 18 '15 at 01:46

0 Answers0