java - x=x+3 和 x+=3 有什么区别?为什么一个需要类型转换而另一个不需要?

标签 java casting compound-operator

问题:

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/

相关文章:

java - java中while循环接收到空字符串时如何输出空行?

python - 在 python 中将 print() 与复合运算符一起使用

Java:+=等价

java - Leiningen:只编译修改过的 java 源文件

java - 在 Spring 表达式语言 (SpEL) 中评估属性

c++ - 类的成员字段顺序是 "stable"吗?

java - Map<String, ?> 如何使用它

c++ - 如何将 CV_64F 类型的 Matrix 转换为具有 Double 元素的一维数组

typescript - 使用逻辑赋值时如何保持类型保护缩小?

Java - Joda时间列表<LocalDate>查找最新日期