Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Short addition questions

Tags:

java

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.

like image 437
Zack Macomber Avatar asked Feb 02 '12 02:02

Zack Macomber


People also ask

Is it += or =+ in Java?

Let's understand the += operator in Java and learn to use it for our day to day programming. x += y in Java is the same as x = x + y. It is a compound assignment operator. Most commonly used for incrementing the value of a variable since x++ only increments the value by one.

Can we add short and int in Java?

Thus, if you add a short to an int, short is the narrower type, so a temporary int with the closest value to the short is created. This temporary int value is added to the other int operand, and results is an int.

Can short be added to INT?

That means that you can save a short value into an int variable, and an int value into a long variable. However, you can't directly store a long variable into an int or short variable.


1 Answers

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).

Edit

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.

like image 69
Dmitri Avatar answered Nov 15 '22 15:11

Dmitri