Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand.
Compound-Assignment Operators in Java
Java supports 11 compound-assignment operators:
+= assigns the result of the addition.
-= assigns the result of the subtraction.
*= assigns the result of the multiplication
/= assigns the result of the division.
%= assigns the remainder of the division.
&= assigns the result of the logical AND.
|= assigns the result of the logical OR.
^= assigns the result of the logical XOR.
<<= assigns the result of the signed left bit shift.
>>= assigns the result of the signed right bit shift.
>>>= assigns the result of the unsigned right bit shift.
Example Usage
To assign the result of an addition operation to a variable using the standard syntax:
//add 2 to the value of number
number = number + 2;
But use a compound-assignment operator to effect the same outcome with the simpler syntax:
//add 2 to the value of number
number += 2;