Let’s see the following expressions in Java.
int temp = -254;
Integer temp2 = (Integer) temp; // compiles because of autoboxing
Integer temp3 = (Integer) -254; // doesn't compile - illegal start of type.
Integer temp4 = (Integer) 10-254; // compiles
Integer temp5 = (Integer) (int) -254; // compiles
Integer temp6 = -254; // compiles
Integer temp7 = (int) -254; // compiles
In the above expressions, why are these expressions (Integer) 10-254 and (int) -254 valid whereas the expression (Integer) -254 doesn’t compile even though the constant -254 can perfectly be evaluated to Integer?
This is an interesting edge case, the compiler attempts to perform integer subtraction on the
Integerclass and anintliteral (254).Note that the following compiles and is more explicit: