什么是“+ =”运营商用Java做什么? [英] What does the "+=" operator do in Java?
问题描述
您能否帮我理解以下代码的含义:
Can you please help me understand what the following code means:
x += 0.1;
推荐答案
编程的常识是 x + = y
是 x = x + y
的等效简写表示法。只要 x
和 y
属于同一类型(例如,两者都是 int
s),您可以认为这两个语句是等价的。
The "common knowledge" of programming is that x += y
is an equivalent shorthand notation of x = x + y
. As long as x
and y
are of the same type (for example, both are int
s), you may consider the two statements equivalent.
然而,在Java中, x + = y
一般与 x = x + y
相同。
However, in Java, x += y
is not identical to x = x + y
in general.
如果 x
且 y
属于不同类型,由于语言规则,这两个语句的行为不同。例如,让我们有 x == 0
(int)和 y == 1.1
(double):
If x
and y
are of different types, the behavior of the two statements differs due to the rules of the language. For example, let's have x == 0
(int) and y == 1.1
(double):
int x = 0;
x += 1.1; // just fine; hidden cast, x == 1 after assignment
x = x + 1.1; // won't compile! 'cannot convert from double to int'
+ =
执行隐式转换,而对于 +
,您需要显式转换第二个操作数,否则会出现编译错误。
+=
performs an implicit cast, whereas for +
you need to explicitly cast the second operand, otherwise you'd get a compiler error.
引自Joshua Bloch的 Java Puzzlers :
Quote from Joshua Bloch's Java Puzzlers:
(...)复合赋值表达式自动将
的计算结果转换为
左侧的变量类型。如果结果的类型与变量的
类型相同,则强制转换无效。但是,如果
结果的类型比变量的类型宽,则复合
赋值运算符执行静默缩小原语
转换[ JLS 5.1.3 ]。
这篇关于什么是“+ =”运营商用Java做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!