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

后端 未结 11 1366
暖寄归人
暖寄归人 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条回答
  •  Happy的楠姐
    2020-11-21 05:36

    The problem here involves type casting.

    When you add int and long,

    1. The int object is casted to long & both are added and you get long object.
    2. but long object cannot be implicitly casted to int. So, you have to do that explicitly.

    But += is coded in such a way that it does type casting. i=(int)(i+m)

提交回复
热议问题