Initializer block - whats the flow of this code?

35 Views Asked by At

I understand that the following code is allowed (I've read the previous posts on the topic), but can someone explain to me what is actually happening when this class is run? Is the block skipped and then "i" is initialized at LINE 7, and then the block is run (setting "i" to 3) and then LINE 7 is run setting "i" to 2?

public class TestClass {

    {
        i = 3;
    }

    int i = 2;      //LINE 7


}
1

There are 1 best solutions below

0
tgdavies On

If we look at the bytecode for the class:

/ class version 62.0 (62)
// access flags 0x21
public class org/kablambda/TestClass {

  // compiled from: TestClass.java

  // access flags 0x0
  I i

  // access flags 0x1
  public <init>()V
   L0
    LINENUMBER 3 L0
    ALOAD 0
    INVOKESPECIAL java/lang/Object.<init> ()V
   L1
    LINENUMBER 6 L1
    ALOAD 0
    ICONST_3
    PUTFIELD org/kablambda/TestClass.i : I
   L2
    LINENUMBER 9 L2
    ALOAD 0
    ICONST_2
    PUTFIELD org/kablambda/TestClass.i : I
    RETURN
   L3
    LOCALVARIABLE this Lorg/kablambda/TestClass; L0 L3 0
    MAXSTACK = 2
    MAXLOCALS = 1
}

We see that the code is run in the same order it appears in the source code, so first i is set to 3, then i is set to 2.