问题:
char x = 'a';
x += 3; // ok
x = x + 3; // compile time error
最佳答案
因为x += 3
等价于x = (char)(x+3)
,而x + 3
默认为int
操作,赋值给char必须强制转换。
来自JLS specification : 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. Note that the implied cast to type T may be either an identity conversion (?.1.1) or a narrowing primitive conversion (?.1.3).
关于java - x=x+3 和 x+=3 有什么区别?为什么一个需要类型转换而另一个不需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6844928/