#### Assignment problems

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 causes a compile time error ?

##### Solution

The final modifier prohibits subsequent assignments to our 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 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 cannot assume the variable i's value to remain unchanged thus possibly receiving a value outside [-128, 127];