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

后端 未结 11 1347
暖寄归人
暖寄归人 2020-11-21 05:06

Until today, I thought that for example:

i += j;

Was just a shortcut for:

i = i + j;

But if we try this:<

11条回答
  •  别那么骄傲
    2020-11-21 05:39

    Very good question. The Java Language specification confirms your suggestion.

    For example, the following code is correct:

    short x = 3;
    x += 4.6;
    

    and results in x having the value 7 because it is equivalent to:

    short x = 3;
    x = (short)(x + 4.6);
    

提交回复
热议问题