Java Short addition questions

随声附和 提交于 2019-12-19 05:48:06

问题


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.


回答1:


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.




回答2:


Here is a good example:

public class Example {
    public static void main(String[] args) {
        Short a = (short) 17;
        a = (short) (a + a);
    }
}


来源:https://stackoverflow.com/questions/9106212/java-short-addition-questions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!