There is no difference, one is shorthand for the other. Even the compiler will generate the same instructions for both.
Edit: the compiler does NOT generate the same code for both, as I just found out. Check this out:
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
}
So the short answer, especially for a Java beginner, or anyone who isn't worried about optimizing at the smallest level, is that they are interchangeable. The long answer will depend on me reading about iadd vs iinc.
Edit 2: Ok, I'm back. The instruction specs are (roughly) as follows:
iadd - adds the top two ints on the stack
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
which is the same thing we get if we have a = a + a
.