class Foo{
public static void main(String args[]){
final int x=101;
int y;
if(x>100){
y=-1;
}
System.out.println(y);
}
}
Java compiler understands the condition of the if statement is always true and therefore y will always be initialized. No compile 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 into two lines, the compiler does not seem to get 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);
Same thing happens here and the compiler gives a loss of precision error.
final int x=101;
byte b;
b=x;
System.out.println(b);
Again, the compiler can understand that x is inside the range of b.
It has to do with how the compiler determines if a statement will be executed or not. It is defined in the JLS #16:
In your case, the compiler can’t determine that
yhas been definitely assigned and gives you an error. This is because it would need to determine that the condition is always true and that is only possible if the condition in theifis a constant expression.JLS #15.28 defines constant expressions:
The JLS #4.12.4 defines constants variables as:
In your case,
final int x = 101;is a constant variable butfinal int x; x = 101;is not.