直到今天,我还以为例如:
i += j;
只是一个捷径:
i = i + j;
但如果我们试试这个:
int i = 5;
long j = 8;
然后 i = i + j;
不会编译,但 i += j;
会编译正常。
这是否意味着实际上 i += j;
是这样的快捷方式
i = (i 的类型) (i + j)
?
最佳答案
与这些问题一样,JLS 提供了答案。在这种情况下 §15.26.2 Compound Assignment Operators .摘录:
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
引用自 §15.26.2 的示例
[...] 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);
换句话说,你的假设是正确的。
关于java - 为什么 Java 的 +=、-=、*=、/= 复合赋值运算符不需要强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8710619/