java中a + = 10和a = a + 10之间的差异?

Gur*_*lki 26 java variable-assignment

a += 10a = a + 10两者是一样的,还是它们之间有一些区别?我在学习Java作业时遇到了这个问题.

Jon*_*eet 33

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
Run Code Online (Sandbox Code Playgroud)

From the Java Language Specification section 15.26.2:

除了仅计算一次之外,表单的复合赋值表达式E1 op= E2等效于 E1 = (T)((E1) op (E2)),where T的类型.E1E1

有趣的是,他们在规范中给出的例子:

short x = 3;
x += 4.6;
Run Code Online (Sandbox Code Playgroud)

在Java中有效,但在C#中没有 ... ...基本上在C#中,编译器执行+ =和 - =的特殊外壳,以确保表达式是目标类型或者是目标类型范围内的文字.


dan*_*ben 17

没有区别,一个是另一个的简写.甚至编译器也会为两者生成相同的指令.

编辑:正如我刚刚发现的那样,编译器不会为两者生成相同的代码.看一下这个:

dan$ cat Test.java
public class Test {
    public static void main(String[] args) {
        int a = 0;
        a = a + 10;
        a += 20;
    }
}

dan$ javap -c Test
Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iload_1
   3:   bipush  10
   5:   iadd
   6:   istore_1
   7:   iinc    1, 20
   10:  return

}
Run Code Online (Sandbox Code Playgroud)

所以简短的答案,特别是对于Java初学者,或任何不担心在最小级别进行优化的人来说,它们是可以互换的.答案很长,取决于我阅读有关iadd vs iinc的内容.

编辑2:好的,我回来了.指令规格(大致)如下:

iadd - 在堆栈上添加前两个整数

iinc - increments a local variable by a constant

And as we saw above, we can save a couple of instructions using iinc, as long as there is a constant on the right hand side.

But what happens if we have

a += a?

Then the code looks like this:

   7:   iload_1
   8:   iload_1
   9:   iadd
   10:  istore_1
Run Code Online (Sandbox Code Playgroud)

which is the same thing we get if we have a = a + a.


mer*_*ike 5

这在Java语言规范第15.25.2节中定义.突出的部分是:

形式E1 op = E2的复合赋值表达式等效于E1 =(T)((E1)op(E2)),其中T是E1的类型,除了E1仅被评估一次.

也就是说,在您的情况下,差异是隐式类型转换:

byte a = 100;
a += 1000;    // compiles
a = a + 1000; // doesn't compile, because an int cannot be assigned to a byte.
Run Code Online (Sandbox Code Playgroud)