Java – Difference Between += and =+ Operators

javaoperatorssyntax

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 gives me the value I expect it to, and the other does not.

Why is this?

Best Answer

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