Java的+ =, - =,* =,/ =复合赋值运算符 [英] Java's +=, -=, *=, /= compound assignment operators
问题描述
直到今天为止,我还是想:例如:
Until today I thought that for example:
i += j;
只是一个捷径:
i = i + j;
但是,如果我们尝试这个:
But what if we try this:
int i = 5;
long j = 8;
然后 i = i + j;
不编译,但 i + = j;
将编译正确。
Then i = i + j;
will not compile but i += j;
will compile fine.
这是否意味着事实上 i + = j;
是类似这样东西的快捷方式
i =(i的类型)(i + j)
?
Does it mean that in fact i += j;
is a shortcut for something like this
i = (type of i) (i + j)
?
推荐答案
与这些问题一样,JLS保留了答案。在这种情况下,§15.26.2复合分配操作符< a>。提取:
As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
以下形式的复合赋值表达式
E1 op = E2
等效于E1 = (T)((E1) (E2))
,其中T
是E1
的类型,除了E1
只计算一次。
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.
[...]
[...] the following code is correct:
short x = 3;
x += 4.6;
,结果x的值为7,因为它等价于:
and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
换句话说,你的假设是正确的。
In other words, your assumption is correct.
这篇关于Java的+ =, - =,* =,/ =复合赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!