考虑这段代码:
byte b=1;
long l=1000;
b += l;
我希望最后一条语句需要显式转换,因为,
b+=l
计算为 b = b+l
并且
(b+l)
部分给出一个整数。
如果没有显式转换,不能将整数分配给字节?
最佳答案
首先,b+l
给出了一个long
,而不是一个int
...
...但是复合赋值运算符有其他行为。根据 JLS section 15.26.2 :
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
注意转换为 T
。
关于java - 为什么这个赋值不需要显式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13603468/