0% completed
Assignment operators are used to assign values to variables in Java. Besides the basic assignment operator (=), Java provides compound assignment operators that combine an arithmetic operation with assignment. These operators simplify your code and improve readability.
| Operator | Description | Example |
|---|---|---|
= | Assigns the value on the right to the variable on the left | a = 10 |
+= | Adds the right operand to the variable and assigns the result to the variable | a += 5 (equivalent to a = a + 5) |
-= | Subtracts the right operand from the variable and assigns the result | a -= 3 (equivalent to a = a - 3) |
*= | Multiplies the variable by the right operand and assigns the result | a *= 2 (equivalent to a = a * 2) |
/= | Divides the variable by the right operand and assigns the result | a /= 4 (equivalent to a = a / 4) |
%= | Applies modulus on the variable by the right operand and assigns the result | a %= 3 (equivalent to a = a % 3) |
Below is an example that demonstrates the use of the basic assignment operator as well as compound assignment operators.
Explanation:
=): The variable a is initially assigned the value 10.+=): The value 5 is added to a, updating it to 15.-=): The value 3 is subtracted from a, updating it to 12.*=): The value a is multiplied by 2, updating it to 24./=): The variable a is divided by 4, updating it to 6.%=): The remainder when a is divided by 4 is assigned back to a, updating it to 2.These examples demonstrate how assignment operators allow you to update variable values succinctly. By using compound operators, you can write cleaner and more efficient code.
.....
.....
.....