Java Short addition questions

后端 未结 2 1076
广开言路
广开言路 2021-01-11 13:04

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:

         


        
相关标签:
2条回答
  • 2021-01-11 13:49

    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.

    0 讨论(0)
  • 2021-01-11 13:52

    Here is a good example:

    public class Example {
        public static void main(String[] args) {
            Short a = (short) 17;
            a = (short) (a + a);
        }
    }
    
    0 讨论(0)
提交回复
热议问题