+1, it looks weird. But essentially, non-static initialization blocks are simply inserted by javac into object constructors. If we decompile arr.class, we get the real code as
public class arr { int index; public arr() { index = 1; } void go() { System.out.println(++index); } public static void main(String args[]) { (new arr()).go(); } }
to get more involved in this puzzle
public class A { int index; A() { index = 2; } { index = 1; } }
what's new A (). index ?. The correct answer is 2. See Decompiled A.class
class A { int index; A() { index = 1; index = 2; } }
that is, non-static initialization blocks are included in object constructors
source share