简体   繁体   中英

Compiler-error while performing type-casting in Java

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 Integer class and an int literal (254).

Note that the following compiles and is more explicit:

    Integer temp3 = (Integer)(-254)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM