The order of the announcement does not matter. You can also write:
public class WhyIsThisOk { { a = 5; } public WhyIsThisOk() { } public static void main(String[] args) { System.out.println(new WhyIsThisOk().a); } int a = 10; }
It is important that the compiler copies (top to bottom) first a=5 , and then a=10 into the constructor, so that it looks like this:
public WhyIsThisOk() { a = 5; a = 10; }
Finally, look at this example:
public class WhyIsThisOk { { a = get5(); } public WhyIsThisOk() { a = get7(); } public static void main(String[] args) { System.out.println(new WhyIsThisOk().a); } int a = get10(); public static int get5() { System.out.println("get5 from: " + new Exception().getStackTrace()[1].getMethodName()); return 5; } public static int get7() { System.out.println("get7 from: " + new Exception().getStackTrace()[1].getMethodName()); return 7; } public static int get10() { System.out.println("get10 from: " + new Exception().getStackTrace()[1].getMethodName()); return 10; } }
Output:
get5 from: <init> get10 from: <init> get7 from: <init> 7
source share