Assignment Operators
3 min read ·
Assignment operators are used to assign values to variables.
They are very important because every program stores and updates data using assignment.
Assignment Operators Table
| Operator | Meaning | Example | Equivalent Expression |
|---|---|---|---|
| = | Assign value | a = 10 | Assign 10 to a |
| += | 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 |
1 Simple Assignment Operator =
Used to assign value to a variable.
Example
2 Addition Assignment Operator +=
Adds value and stores result in same variable.
Example
Explanation
score += 10 means score = score + 10
3 Subtraction Assignment Operator -=
Subtracts value and stores result.
4 Multiplication Assignment Operator *=
Multiplies and assigns result.
5 Division Assignment Operator /=
Divides and assigns result.
6 Modulus Assignment Operator %=
Stores remainder after division.
Assignment Operators with Different Data Types
Java automatically converts smaller types when required.
Important Concept
Assignment operators reduce code length and improve readability.
Instead of writing
total = total + 5
You can write
total += 5
Real World Example
Updating Bank Account Balance
Caution
Be careful while using division assignment with integers because decimal part will be removed.