Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any idea why I need to cast an integer literal to (int) here?

People also ask

What does casting to an int do?

Casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative.

How do you cast an integer to a number?

You can't cast from int to Number because int is a primitive type and Number is an object. Casting an object is changing the reference type from one type of object to another. You first have to have an object to work with.

What is an int literal?

Integer literals are numbers that do not have a decimal point or an exponential part. They can be represented as: Decimal integer literals. Hexadecimal integer literals.


The compiler tries to subtract 128 from (Integer) instead of casting -128 to Integer. Add () to fix it

Integer i3 = (Integer) -128; // doesn't compile
Integer i3 = (Integer) (-128); // compiles

According to BoltClock in the comments the cast to int works as intended, because it is a reserved word and therefore can't be interpreted as an identifier, which makes sense to me.

And Bringer128 found the JLS Reference 15.16.

 CastExpression:
    ( PrimitiveType Dimsopt ) UnaryExpression
    ( ReferenceType ) UnaryExpressionNotPlusMinus

As you can see, casting to a primitive type requires any UnaryExpression, whereas casting to a reference type requires a UnaryExpressionNotPlusMinus. These are defined just before the CastExpression at JLS 15.15.


I found the JLS reference. 15.16.

 CastExpression:
    ( PrimitiveType Dimsopt ) UnaryExpression
    ( ReferenceType ) UnaryExpressionNotPlusMinus

As you can see, casting to a primitive type requires any UnaryExpression, whereas casting to a reference type requires a UnaryExpressionNotPlusMinus. These are defined just before the CastExpression at JLS 15.15.

You need to either change the cast to a primitive type:

... (int) -128;

Or you can change the expression to the right of the cast to a non-plus-minus unary expression:

... (Integer) (-128);  // Either
... (Integer) 0 - 128; // Or

The compiler interprets the - as the two-arg minus operator, i.e. it's trying to subtract 128 from some other number named Integer, but there's no such variable in scope.

This compiles:

Integer i3 = (Integer) (-128)

This may have to do with syntax parsing. Notice that

Integer i4 = (Integer) (-128); 

works just fine.

In general, you should not cast to Integer class. This involves something called auto-boxing, and can cause some subtle errors in your code. The prefered method of doing what you want is:

Integer i6 = Integer.valueOf(-128)