I\'ve misplaced += with =+ one too many times, and I think I keep forgetting because I don\'t know the difference between these two, only that one
Some historical perspective: Java inherited the += and similar operators from C. In very early versions of C (mid 1970s), the compound assignment operators had the "=" on the left, so
x =- 3;
was equivalent to
x = x - 3;
(except that x is only evaluated once).
This caused confusion, because
x=-1;
would decrement x rather than assigning the value -1 to it, so the syntax was changed (avoiding the horror of having to surround operators with blanks: x = -1;).
(I used -= and =- in the examples because early C didn't have the unary + operator.)
Fortunately, Java was invented long after C changed to the current syntax, so it never had this particular problem.
a += b is short-hand for a = a + b (though note that the expression a will only be evaluated once.)
a =+ b is a = (+b), i.e. assigning the unary + of b to a.
Examples:
int a = 15;
int b = -5;
a += b; // a is now 10
a =+ b; // a is now -5
Because =+ is not a Java operator.
a += b equals a = a + b. a =+ b equals a = (+b).
+= → Add the right side to the left
=+ → Don't use this. Set the left to the right side.
x += y
is the same as
x = x + y
and
x =+ y
is wrong but could be interpreted as
x = 0 + y