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

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

    In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:

     byte -> short -> int -> long -> float -> double. 

    The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
    Type - Conversion

提交回复
热议问题