class Foo{ public static void main(String args[]){ final int x=101; int y; if(x>100){ y=-1; } System.out.println(y); } }
The Java compiler understands that the condition of the if statement is always true, and therefore, y will always be initialized. Compilation error, as expected.
class Bar{ public static void main(String args[]){ final int x; x=101; int y; if(x>100){ y=-1; } System.out.println(y); } }
But when I break the declaration and initialization of x on two lines, the compiler does not seem that the condition is always true, and y will always be initialized.
final int x; x=101; byte b; b=x; System.out.println(b);
The same thing happens here, and the compiler gives a loss of error accuracy.
final int x=101; byte b; b=x; System.out.println(b);
Again, the compiler can understand that x is inside range b.
java initialization conditional final
PrashanD Nov 05 2018-12-12T00: 00Z
source share