简写赋值运算符,+ =,是真的吗? [英] Short hand assignment operator, +=, True Meaning?
问题描述
我了解到i+=2
是i=i+2
的简写.但是现在我对此表示怀疑.
对于以下代码,以上知识没有帮助:
I learnt that i+=2
is the short-hand of i=i+2
. But now am doubting it.
For the following code, the above knowledge holds no good:
byte b=0;
b = b + 2;//错误:必填字节,找到int
byte b=0;
b=b+2; //Error:Required byte, Found int
上面的代码是合理的,因为2
是int
类型,并且表达式返回int
值.
The above code is justifiable, as 2
is int
type and the expression returns int
value.
但是,以下代码运行良好:
But, the following code runs fine:
byte b=0; b+=2; //b stores 2 after += operation
这迫使我怀疑+=
速记运算符比我所知道的还要更多.
请赐教.
This is forcing me to doubt that the +=
short-hand operator is somewhat more than I know.
Please enlighten me.
推荐答案
如有疑问,您可以随时检查Java语言规范.在这种情况下,相关部分是15.26.2,复合赋值运算符.
When in doubt, you can always check the Java Language Specification. In this case, the relevant section is 15.26.2, Compound Assignment Operators.
形式为E1 op = E2的复合赋值表达式是等效的 到E1 =(T)((E1)op(E2)),其中T是E1的类型,只是E1仅被评估一次.
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.
因此,您几乎是正确的,除了还添加了强制类型转换.在您的情况下:
b+=2;
符合b=(byte)(b+2);
So you were almost correct, except that a cast is added as well. In your case:
b+=2;
qualifies to b=(byte)(b+2);
这篇关于简写赋值运算符,+ =,是真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!