Shortcut Assignment Operators

We can use the following shortcut operators in the assignment of variables:

Operator Example Equivalent To
+= i += 8; i = i + 8;
-= i -= 2.0; i = i – 2.0;
*= i *= 13; i = i * 13;
/= i /= 5; i = i / 5;
%= i %= 2; i = i % 2;


Incrementing and decrementing a value by one is so common, there are special (even shorter) shortcut operators for these tasks:

Operator
(applied to myVar)
Name Description
++myVar Pre-Increment The expression (++myVar) adds 1 to myVar, and if used in or as an expression, it evaluates to this new (incremented) value of myVar.
myVar++ Post-Increment The expression (myVar++) also adds 1 to myVar, but if used in or as an expression, it evaluates to the original value of myVar (before the increment)
--myVar Pre-Decrement The expression (‐‐myVar) subtracts 1 from myVar, and if used in or as an expression, it evaluates to this new (decremented) value of myVar.
myVar-- Post-Decrement The expression (myVar‐‐) also subtracts 1 from myVar, but if used in or as an expression, it evaluates to the original value of myVar (before the decrement)

Be careful about using the increment and decrement operators within an expression. Consider the following examples:

int i = 5;
int n = 3 * i++;
  has the same effect as  
int i = 5;
int n = 3 * i;
i = i + 1;

while

int i = 5;
int n = 3 * ++i;
  has the same effect as  
int i = 5;
i = i + 1;
int n = 3 * i;