Assignment Operators
Assignment operators in Java are used to assign values to variables. In addition to the simple assignment (=), Java provides compound assignment operators that combine arithmetic (or bitwise) operations with assignment.
This topic is important for clean coding, performance, and interviews.
What Are Assignment Operators?
- Assign values to variables
- Can combine operation + assignment
- Improve code readability and conciseness
Types of Assignment Operators
Java supports:
- Simple Assignment Operator
- Compound Assignment Operators
1. Simple Assignment Operator (=)
Assigns the value on the right-hand side to the variable on the left-hand side.
int a = 10;
Chained Assignment
int x, y, z;
x = y = z = 5;
Why it matters: Assignment happens right to left.
2. Compound Assignment Operators
Combine an operation with assignment.
| Operator | Example | Equivalent To |
|---|---|---|
| += | a += b | a = a + b |
| -= | a -= b | a = a - b |
| *= | a *= b | a = a * b |
| /= | a /= b | a = a / b |
| %= | a %= b | a = a % b |
Example: +=
int a = 10;
a += 5; // a = 15
Example: -=
int a = 20;
a -= 8; // a = 12
Example: *=
int a = 4;
a *= 3; // a = 12
Example: /=
int a = 10;
a /= 3; // a = 3
Example: %=
int a = 10;
a %= 3; // a = 1
Implicit Type Casting in Compound Assignment (Important Interview Point)
Compound assignment operators perform implicit casting.
byte b = 10;
b += 5; // ✅ allowed
Equivalent expanded form:
b = (byte)(b + 5);
Compare with Simple Assignment
byte b = 10;
b = b + 5; // ❌ compilation error
Why it matters: Compound operators automatically cast the result to the variable type.
Assignment with Different Data Types
int a = 10;
double d = 2.5;
a += d; // a = 12 (fraction lost)
Assignment Operators with Strings
String s = "Java";
s += " Programming";
System.out.println(s); // Java Programming
Note: Creates a new String object (String is immutable).
Operator Precedence (Quick Note)
- Assignment operators have lower precedence than arithmetic operators
- Evaluated right to left
int x = 10 + 5 * 2; // x = 20
Common Beginner Mistakes
- Confusing = with ==
- Ignoring implicit casting in compound assignments
- Expecting rounding instead of truncation
- Overusing compound operators leading to unclear code
Interview-Ready Answers
Short Answer
Assignment operators assign values to variables and can combine arithmetic operations with assignment.
Detailed Answer
Java assignment operators include the simple assignment (=) and compound operators like +=, -=, *=, /=, and %=. Compound operators simplify code and perform implicit type casting, making them concise but requiring careful usage.
Key Takeaway
Assignment operators make code concise and readable, but understanding implicit casting and evaluation order is essential to avoid subtle bugs.