Compound assignment operators in Java are used to perform an operation on a variable and then assign the result back to that variable in a concise way. These operators combine both an arithmetic operation and assignment in a single step. Using compound assignment operators can make your code more readable and shorter.
Here’s a list of the compound assignment operators in Java:
Addition assignment (
+=
): Adds the right operand to the left operand and assigns the result to the left operand.javaint a = 5;
a += 2; // Equivalent to a = a + 2; Now, a is 7.
Subtraction assignment (
-=
): Subtracts the right operand from the left operand and assigns the result to the left operand.javaint b = 5;
b -= 2; // Equivalent to b = b - 2; Now, b is 3.
Multiplication assignment (
*=
): Multiplies the left operand by the right operand and assigns the result to the left operand.javaint c = 3;
c *= 2; // Equivalent to c = c * 2; Now, c is 6.
Division assignment (
/=
): Divides the left operand by the right operand and assigns the result to the left operand.javaint d = 6;
d /= 2; // Equivalent to d = d / 2; Now, d is 3.
Modulus assignment (
%=
): Takes the modulus using two operands and assigns the result to the left operand.javaint e = 5;
e %= 2; // Equivalent to e = e % 2; Now, e is 1.
Other compound assignment operators include:
- Bitwise AND assignment (
&=
): Performs a bitwise AND on both operands and assigns the result to the left operand. - Bitwise OR assignment (
|=
): Performs a bitwise OR on both operands and assigns the result to the left operand. - Bitwise XOR assignment (
^=
): Performs a bitwise XOR on both operands and assigns the result to the left operand. - Left shift assignment (
<<=
): Shifts the left operand left by the number of bits specified by the right operand and assigns the result to the left operand. - Right shift assignment (
>>=
): Shifts the left operand right by the number of bits specified by the right operand and assigns the result to the left operand. - Unsigned right shift assignment (
>>>=
): Shifts the left operand right (unsigned) by the number of bits specified by the right operand and assigns the result to the left operand.
Using these operators can simplify your code and make it more efficient by reducing the verbosity of common mathematical and bitwise operations.