java中a + = 10和a = a + 10之间的区别? [英] Difference between a += 10 and a = a + 10 in java?
问题描述
a + = 10
和 a = a + 10
两者是否相同,或者是否存在一些差异他们?我在用Java学习作业时遇到了这个问题。
Are a += 10
and a = a + 10
both the same, or is there some difference between them? I got this question while studying assignments in Java.
推荐答案
正如你现在提到的那样... ...这种情况:
As you've now mentioned casting... there is a difference in this case:
byte a = 5;
a += 10; // Valid
a = a + 10; // Invalid, as the expression "a + 10" is of type int
来自Java语言规范部15.26.2 :
From the Java Language Specification section 15.26.2:
形式
E1 op = E2
的复合赋值表达式相当于
E1 =(T)((E1)op(E2))
,其中T
是<$ c $的类型c> 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.
有趣的是,他们在规范中给出的例子:
Interestingly, the example they give in the spec:
short x = 3;
x += 4.6;
在Java中有效,但在C#中不是 ...基本上在C#编译器执行+ =和 - =的特殊外壳,以确保表达式是目标类型或文件在目标类型范围内的文字。
is valid in Java, but not in C#... basically in C# the compiler performs special-casing of += and -= to ensure that the expression is either of the target type or is a literal within the target type's range.
这篇关于java中a + = 10和a = a + 10之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!