Adding int to short

This question already has an answer here:

  • Why don't Java's +=, -=, *=, /= compound assignment operators require casting? 11 answers

  • int i = 123456;
    short x = 12;
    x += i;
    

    is actually

    int i = 123456;
    short x = 12;
    x = (short)(x + i);
    

    Whereas x = x + i is simply x = x + i . It does not automatically cast as a short and hence causes the error ( x + i is of type int ).


    A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)) , where T is the type of E1 , except that E1 is evaluated only once.

    - JLS §15.26.2


    Numbers are treated as int unless you specifically cast them otherwise. So in the second statement when you use a literal number instead of a variable, it doesn't automatically cast it to the appropriate type.

    x = x + (short)1;
    

    ...should work.


    The + operator of integral types (int, short, char and byte) always returns an int as result.

    You can see that with this code:

    //char x = 0;
    //short x = 0;
    //byte x = 0;
    int x = 0;
    x = x + x;
    

    It won't compile unless x is an int .

    链接地址: http://www.djcxy.com/p/12784.html

    上一篇: Java int + =双语法惊喜

    下一篇: 将int加到short