121

In the following example

int i = -128;
Integer i2 = (Integer) i; // compiles

Integer i3 = (Integer) -128; /*** Doesn't compile ***/

Integer i4 = (Integer) (int) -128; // compiles
Integer i4 = -128; // compiles
Integer i5 = (int) -128; // compiles
Integer i6 = (Integer) (-128); // compiles
Integer i7 = (Integer) 0-128; // compiles

I can't cast -128 with (Integer) but I can cast (int) -128.

I always thought -128 was of int type and casting it with (int) should be redundant.

The error on the line with i3 is

cannot find symbol variable Integer

I tried this with Java 6 update 29 and Java 7 update 1.

EDIT: You get the same behavior with +128 instead of -128. It does appear to be confusion between unary and binary operators.

12
  • 5
    what's your compiler? Integer i = -128; this should compile, though.
    – bestsss
    Oct 26, 2011 at 8:16
  • wierd, Integer i3 = (Integer) (-128); complies though.
    – Eng.Fouad
    Oct 26, 2011 at 8:18
  • 2
    @Eng.Fouad, Peter, unary symbols (+-) have right to left associativity and plus, minus are left to right. The effect of -128 would be the same as +128 and putting 0 in front should fix, i.e. 0-128 or 0+128. (cant test atm but I bet it will)
    – bestsss
    Oct 26, 2011 at 8:26
  • Good question! I'd personally like to see a JLS reference for the resolution of unary/binary operators and when a cast is treated as an expression. Otherwise, it might be possible that other compilers do not consider it an error!
    – user545680
    Oct 26, 2011 at 8:31
  • 1
    Also FYI the error I get in my IDE is Expression expected where the Integer is.
    – user545680
    Oct 26, 2011 at 8:32

8 Answers 8

150

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.

8
  • 31
    I think it's because int is a keyword in Java, but Integer is not. Since int is a keyword, you can't use it as an identifier for a variable or a class, leaving the only possibility left for it to be a typecast. That'd explain it.
    – BoltClock
    Oct 26, 2011 at 8:23
  • @BoltClock Incorporated your comment in the answer. Oct 26, 2011 at 8:28
  • 3
    To make this an even more stellar answer, do you want to add my link to the JLS?
    – user545680
    Oct 26, 2011 at 8:50
  • 3
    An interesting (to me) wrinkle on this issue is how we solve the analogous problem in C#, which also has an ambiguity in the grammar between "parenthesized expression as an operand to binary subtraction operator" and "cast operator where the right operand of the cast is a unary minus expression". See section 7.7.6 of the C# specification for a detailed description of the heuristics we use to try and be smart about resolving the amgiguity. Oct 26, 2011 at 18:21
  • 1
    @BillK Why do you say that? The C# spec doesn't refer to operator overloading in section 7.7.6, so it wasn't an issue for them.
    – user545680
    Oct 27, 2011 at 2:12
48

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
11

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)
2
  • You could add a comment on why (int) makes a difference. Oct 26, 2011 at 8:22
  • 1
    It's due to the autoboxing, no? Oct 26, 2011 at 8:23
8

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)
5
  • 1
    cast to Integer is exactly synthetic sugar for valueOf.
    – bestsss
    Oct 26, 2011 at 8:22
  • 4
    yes, but sometimes the synthetic sugar fails in subtle ways. I've had some hard to track down null pointer exceptions in large applications due to auto-boxing. We went as far as treating auto-boxing as errors in order to save headaches in the future. Magic is nice, but when it fails, heads hurt. I find it is better to be explicit and save yourself the headaches. Oct 26, 2011 at 8:24
  • NPE are b1tch w/ outboxing, true. Esp cases like for (int i in Collection<Integer>) b/c the NPE is at absolutely unexpected location. I actually do not use Integer w/ autoboxing since the cache range is small (albeit it can be increased w/ XX option) but have a class called IntegerProvider (since 1.1) to do the very same stuff. Using Map (any from java.util) Integer->Anything is usually a performance hit unless it's used for trivial cases and almost always there is a better solution.
    – bestsss
    Oct 26, 2011 at 8:34
  • Casting int to Integer can never cause any errors, except heap overflow, perhaps. The inverse is not true, though.
    – Ingo
    Oct 26, 2011 at 8:43
  • @MattBall, I dont quite get it, synthetic sugar is used widely: eggcorns.lascribe.net/forum/viewtopic.php?id=4400 and synthetic sounds better to me.
    – bestsss
    Oct 26, 2011 at 17:39
8

It's parsing it as Integer <minus operator> 128 and not finding the variable Integer. You'll need to wrap the -128 in brackets:

Integer i3 = (Integer) (-128);  // compiles
1
  • I've awarded +1 to all other answers cos they're all correct too :)
    – Bohemian
    Oct 26, 2011 at 8:23
6
Integer i3 = (Integer) (-128);

The problem is the - The compiler sees it as an operator.

5

Line 3 is interpreted like you're trying to deduct 128 from the expression in the parenthesis and the expression in the parenthesis is not and expression of type int (It treats the '-' as a '-' operator). If you change the expression to:

Integer i3 = (Integer) (-128);

then the compiler will understand the '-' is the unary minus that indicates a negative integer.

2

The C# compiler has the same behaviour. It gives a better hint why it fails to compile though:

To cast a negative value, you must enclose the value in parentheses

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.