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:
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.
Here is a good example:
public class Example {
public static void main(String[] args) {
Short a = (short) 17;
a = (short) (a + a);
}
}