Reputation: 6905
This may have already been answered in another post, but I just am not getting why something won't compile in my test Java app (1.7.0_01).
This compiles:
Short a = (short)17;
a = (short)2 + 1;
I know that "a + a" will result in an integer. This compiles fine:
Short a = (short)17;
int shortTest = a + a;
So why doesn't this compile?
Short a = (short)17;
a = (short)a + a;
Also, am I right to assume you can't use +=, -=, etc... on Shorts because of the conversion to integer? If it's possible to do those operations, can someone provide an example?
Edit 1
There's been some votes to close this post as it's been suggested that it's a duplicate of Primitive type 'short' - casting in Java. However, my example revolves around the Wrapper "Short" object. There are important and more complicated rules around casting Wrapper objects and that's what I think needs to be focussed on.
Also, as my original post indicates, I'm looking for the "why" behind the 3rd code block. I'm also interested to know if it's possible to use "+=", "-=", etc... on the Short Wrapper.
Upvotes: 14
Views: 19560
Reputation: 9157
Seems the correct answer was removed for some reason: (short) a + a
is equivalent to ((short) a) + a
, you're looking for (short)(a + a)
.
The 'why' behind it is operator precedence, same reason why 1 + 2 * 3
is 7
and not 9
. And yes, primitives and literals are treated the same.
You can't do Short s = 1; s += 1;
because it's the same as a = a + 1;
where a is converted to an int
and an int
can't be cast to a Short
. You can fix the long version like so: a = (short) (a + 1);
, but there's no way to get the explicit cast in there with +=
.
It's pretty annoying.
Upvotes: 13