Compiler error when doing type casting in Java

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, while the expression (Integer) -254 not compiled, although the constant -254 can be perfectly evaluated to Integer ?

+4
source share
2 answers

This is an interesting edge case, the compiler is trying to perform integer subtraction in the class Integer and literal int (254).

Note that the following compilations are more explicit:

  Integer temp3 = (Integer)(-254) 
+4
source

In particular, this corresponds to section 15.16 of the third edition of the JLS :

The expression expressed converts at run time the value of one numeric type to the same value of another numeric type; or confirms, when compiling, the time when the type of the expression is Boolean; or checking, at startup, that the reference value refers to an object whose class is compatible with the specified reference type.

CastExpression:
(PrimitiveType Dimsopt) UnaryExpression
(ReferenceType) UnaryExpressionNotPlusMinus

+3
source

Source: https://habr.com/ru/post/1387951/


All Articles