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

后端 未结 11 1344
暖寄归人
暖寄归人 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:29

    Subtle point here...

    There is an implicit typecast for i+j when j is a double and i is an int. Java ALWAYS converts an integer into a double when there is an operation between them.

    To clarify i+=j where i is an integer and j is a double can be described as

    i = (i + j)
    

    See: this description of implicit casting

    You might want to typecast j to (int) in this case for clarity.

提交回复
热议问题