What is the difference between a += b and a =+ b , also a++ and ++a?

a += b is equivalent to a = a + b

a = +b is equivalent to a = b

a++ and ++a both increment a by 1. The difference is that a++ returns the value of a before the increment whereas ++a returns the value after the increment.

That is:

a = 10;
b = ++a; //a = 11, b = 11

a = 10;
b = a++; //a = 11, b = 10

a += b is equivalent to a = a + b

a = +b is equivalent to a = b

a++ is postfix increment and ++a is prefix increment. They do not differ when used in a standalone statement, however their evaluation result differs: a++ returns the value of a before incrementing, while ++a after. I.e.

int a = 1;
int b = a++; // result: b == 1, a == 2
int c = ++a; // result: c == 3, a == 3

Tags:

Java