Some may find it similar to a SO question. Do Java Final variables complete default values? , but this answer does not completely solve this, since this question does not directly print the value of x inside the instance initializer block.
The problem occurs when I try to print x directly inside the instance initializer block by assigning the value x to the end of the block:
Case 1
class HelloWorld { final int x; { System.out.println(x); x = 7; System.out.println(x); } HelloWorld() { System.out.println("hi"); } public static void main(String[] args) { HelloWorld t = new HelloWorld(); } }
This gives a compile-time error indicating that the variable x was not initialized.
$ javac HelloWorld.java HelloWorld.java:6: error: variable x might not have been initialized System.out.println(x); ^ 1 error
Case 2
Instead of direct printing, I call the function to print:
class HelloWorld { final int x; { printX(); x = 7; printX(); } HelloWorld() { System.out.println("hi"); } void printX() { System.out.println(x); } public static void main(String[] args) { HelloWorld t = new HelloWorld(); } }
This compiles correctly and produces the result.
0 7 hi
What is the conceptual difference between the two cases?
java initialization final
Ashwani Kumar Rahul Nov 30 '15 at 9:35 2015-11-30 09:35
source share