java - 为什么 Java 的 +=、-=、*=、/= 复合赋值运算符不需要强制转换?

标签 java casting operators variable-assignment assignment-operator

直到今天,我还以为例如:

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 to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 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/

相关文章:

actionscript-3 - 将 < 或 > 运算符作为参数传递给函数?

c++ - 一个运算符 == 其参数是非常量引用

java - 在 java 中使用 HashMap 的主要好处是什么?

Swift,可选的包装器。 "?" "!"我明白它是如何工作的。但为什么它比 != nil 检查更好

java - 使用增量运算符打印 1 到 10

c++ - 将 vector <int>转换为const vector <const int>

mysql - 在 MySQL 中转换为十进制

运行 nodetool cleanup 时出现 java.lang.ClassCastException 和 java.lang.AssertionError

java - 在缓存中添加文件时出现 FileNotFoundException - Hadoop - Mapreduce

Java - 从 PHP 网页 URL 读取一个 txt 文件