Assignment problems

exercise No. 267

Q:

We consider:

Code Result
final int i = 33;
byte b = i;
Compiles flawlessly.
int i = 33;
byte b = i;
Compile time Error: 
Incompatible types.
Required: byte
Found: int

Give an explanation: Why does the first snippet compiles flawlessly but the second second is causing a compile time error ?

A:

The final modifier prohibits subsequent assignments to the variable i. The compiler can thus safely assume its value to remain constant. The int value of 33 fits nicely into a byte variable ranging from -128 to 127. With respect just to the assignment of variable b the first code snippet is equivalent to:

byte b = 33; // int to byte narrowing by compile time range check

Without the final modifier in general a more complex compile time analysis would be required. (Standard) Java™ compilers do not implement this. Albeit no statement being present between the two lines the compiler does not assume the variable i's value to remain unchanged thus possibly encountering a value outside the [-128, 127] range;