Assignment Operators in Java:
Assignment operators are used to assign values to variables.
The most common operator is =, but Java also supports compound assignment operators like +=, -=, etc., which perform an operation and assign the result in one step.
List of Assignment Operators:
| Operator | Description | Example | Equivalent To |
|---|---|---|---|
| = | Assign value | a = 10 | a = 10 |
| += | Add and assign | a += 5 | a = a + 5 |
| -= | Subtract and assign | a -= 3 | a = a - 3 |
| *= | Multiply and assign | a *= 2 | a = a * 2 |
| /= | Divide and assign | a /= 4 | a = a / 4 |
| %= | Modulus and assign | a %= 3 | a = a % 3 |
Notes:
- Assignment operators modify the variable's current value.
- They help in writing shorter, cleaner code.
- Commonly used in loops and mathematical calculations.
- Work with all numeric types (int, float, double, etc.).
Example:
class ShikshaSanchar {
public static void main(String[] args) {
int a = 10;
a += 5; // a = a + 5 → 15
a -= 2; // a = a - 2 → 13
a *= 2; // a = a * 2 → 26
a /= 2; // a = a / 2 → 13
a %= 4; // a = a % 4 → 1
System.out.println("Final value of a: " + a);
}
}
Output:
Final value of a: 1
Explanation:
- a is first assigned 10.
- a += 5 adds 5 → a = 15
- a -= 2 subtracts 2 → a = 13
- a *= 2 doubles it → a = 26
- a /= 2 divides by 2 → a = 13
- a %= 4 gives remainder when divided by 4 → a = 1
Finally, the result 1 is printed.
Summary:
- Assignment operators allow efficient value updates.
- Use +=, -=, etc., to avoid writing repetitive code like a = a + 5.
- Very useful in loops, conditions, and calculations.
- Mastering them helps you write cleaner and more efficient Java code.