Reputation: 19027
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
?
Upvotes: 4
Views: 194
Reputation: 2670
This is an interesting edge case, the compiler attempts to perform integer subtraction on the Integer
class and an int
literal (254).
Note that the following compiles and is more explicit:
Integer temp3 = (Integer)(-254)
Upvotes: 4
Reputation: 23208
More specifically, this is in accordance with the section 15.16 of the JLS 3rd edition:
A cast expression converts, at run time, a value of one numeric type to a similar value of another numeric type; or confirms, at compile time, that the type of an expression is boolean; or checks, at run time, that a reference value refers to an object whose class is compatible with a specified reference type.
CastExpression:
( PrimitiveType Dimsopt ) UnaryExpression
( ReferenceType ) UnaryExpressionNotPlusMinus
Upvotes: 3