Assignment Operators in Java – Explained with Examples
Assignment operators store values in variables. The basic one is =, and Java also offers compound assignment operators such as += and *=, which combine an operation with assignment in one short step.
This tutorial covers every assignment operator, the hidden cast inside compound assignments, chained assignments, using an assignment as an expression, and what assignment means for objects and arrays.
1. The Simple Assignment Operator =
= evaluates the expression on its right and stores the result in the variable on its left:
int score = 0; // initialise
score = 75; // replace the value
score = score + 10; // read, calculate, then store: 85
String name = "Asha";
The left side must be a variable (or an array element or field); 5 = x; is a compile error. Remember that = assigns, while == compares.
2. Compound Assignment Operators
| Operator | Example | Same as |
|---|---|---|
+= | x += 5 | x = x + 5 (also appends to strings) |
-= | x -= 3 | x = x - 3 |
*= | x *= 2 | x = x * 2 |
/= | x /= 4 | x = x / 4 |
%= | x %= 7 | x = x % 7 |
&=, |=, ^= | f &= mask | f = f & mask (bitwise) |
<<=, >>=, >>>= | f <<= 2 | f = f << 2 (shifts) |
public class CompoundAssignment {
public static void main(String[] args) {
int x = 20;
System.out.println("x = 20");
x += 5; System.out.println("x += 5 -> " + x);
x -= 3; System.out.println("x -= 3 -> " + x);
x *= 2; System.out.println("x *= 2 -> " + x);
x /= 4; System.out.println("x /= 4 -> " + x);
x %= 7; System.out.println("x %= 7 -> " + x);
int flags = 0b1100;
flags &= 0b1010; System.out.println("flags &= 1010 -> " + Integer.toBinaryString(flags));
flags |= 0b0001; System.out.println("flags |= 0001 -> " + Integer.toBinaryString(flags));
flags ^= 0b1111; System.out.println("flags ^= 1111 -> " + Integer.toBinaryString(flags));
flags <<= 2; System.out.println("flags <<= 2 -> " + Integer.toBinaryString(flags));
flags >>= 1; System.out.println("flags >>= 1 -> " + Integer.toBinaryString(flags));
String message = "Hello";
message += ", Java";
System.out.println(message);
}
}
x = 20 x += 5 -> 25 x -= 3 -> 22 x *= 2 -> 44 x /= 4 -> 11 x %= 7 -> 4 flags &= 1010 -> 1000 flags |= 0001 -> 1001 flags ^= 1111 -> 110 flags <<= 2 -> 11000 flags >>= 1 -> 1100 Hello, Java
3. The Hidden Cast in Compound Assignment
A compound assignment x op= y really means x = (Type of x) (x op y). That built-in cast makes some code compile that would otherwise fail, and it can also hide overflow or lost fractions:
public class ImplicitCast {
public static void main(String[] args) {
byte level = 10;
// level = level + 5; // compile error: possible lossy conversion from int to byte
level += 5; // OK: compound assignment casts automatically
System.out.println("level = " + level);
byte small = 120;
small += 10; // silently overflows past 127
System.out.println("small = " + small);
char letter = 'A';
letter += 2; // works on char too
System.out.println("letter = " + letter);
int total = 10;
total += 2.9; // the double result is cast back to int
System.out.println("total = " + total);
}
}
level = 15 small = -126 letter = C total = 12
level = level + 5fails becauselevel + 5is anint;level += 5compiles thanks to the cast.small += 10silently wraps from 130 to-126, because abytecan only hold up to 127.total += 2.9adds 2.9 and then truncates back toint, giving 12.
4. Chained Assignment and Assignment as an Expression
An assignment is itself an expression, and its value is the value that was assigned. Assignment is right-associative, so a = b = c = 5 works from right to left. The same property allows the common "read until end" loop:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class AssignmentExpression {
public static void main(String[] args) throws IOException {
// Chained assignment works right to left
int a, b, c;
a = b = c = 5;
System.out.println("a=" + a + " b=" + b + " c=" + c);
// An assignment is an expression whose value is the assigned value
BufferedReader reader = new BufferedReader(new StringReader("first\nsecond\nthird"));
String line;
int count = 0;
while ((line = reader.readLine()) != null) { // assign, then test
count++;
System.out.println(count + ": " + line);
}
}
}
a=5 b=5 c=5 1: first 2: second 3: third
The parentheses in (line = reader.readLine()) != null are required, because != has higher precedence than =.
5. Assigning References: Objects and Arrays
For object and array variables, = copies the reference, not the object. Both variables then refer to the same object, and a change through one is visible through the other:
import java.util.Arrays;
public class ReferenceAssignment {
public static void main(String[] args) {
int[] original = {1, 2, 3};
int[] alias = original; // copies the reference, not the array
alias[0] = 99;
System.out.println("original = " + Arrays.toString(original));
int[] copy = original.clone(); // a real copy
copy[1] = 42;
System.out.println("original = " + Arrays.toString(original) + ", copy = " + Arrays.toString(copy));
}
}
original = [99, 2, 3] original = [99, 2, 3], copy = [99, 42, 3]
To get an independent copy, use clone(), Arrays.copyOf(), a copy constructor or List.copyOf().
6. Assignment and final
A final variable can be assigned exactly once. Any further assignment, including compound ones such as MAX += 1, is a compile error. See final keyword in Java.
7. Using += with Strings
+= on a String creates a new string each time, because strings are immutable. That is fine for a few joins, but in large loops use a StringBuilder:
// Fine for small amounts
String csv = "";
csv += "a,";
csv += "b";
// Better in loops
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i).append(',');
}
String result = sb.toString();
8. Common Mistakes
- Writing
if (x = 5)instead ofif (x == 5). In Java this does not compile forint, but withbooleanvariablesif (done = true)compiles and is always true. - Writing
x =+ 5(which assigns+5) instead ofx += 5. - Relying on the hidden cast in
+=and missing an overflow. - Expecting
b = ato copy an array or object.
9. Summary
=stores the value of the right side in the variable on the left.- Compound operators (
+=,-=,*=,/=,%=, bitwise and shift variants) combine an operation with assignment. - Compound assignment includes an implicit cast to the variable's type.
- Assignment is right-associative and is itself an expression.
- Assigning an object or array copies the reference only.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What is the assignment operator in Java?
The = operator, which stores the value of the expression on its right in the variable on its left, for example int x = 10;.
Q2. What are compound assignment operators?
Operators that combine an operation with assignment: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= and >>>=.
Q3. Is x += 1 exactly the same as x = x + 1?
Almost. x += 1 includes an automatic cast back to the type of x and evaluates x only once. That is why byte b = 1; b += 1; compiles but b = b + 1; does not.
Q4. Why does byte b += 5 compile but b = b + 5 does not?
b + 5 is an int, which cannot be assigned to a byte without a cast. Compound assignment includes that cast automatically.
Q5. What is the difference between = and ==?
= assigns a value; == compares two values and returns a boolean.
Q6. Can I assign multiple variables at once?
Yes, with chained assignment: a = b = c = 0;. Java evaluates it right to left. The variables must already be declared.
Q7. What does an assignment expression return?
The value that was assigned. This is why while ((line = reader.readLine()) != null) works: the assignment's value is compared with null.
Q8. What is the associativity of assignment operators?
Right to left. In a = b = 5, b = 5 runs first and its value is then assigned to a.
Q9. Does += work with strings?
Yes. s += "text" concatenates and stores a new string. In loops with many concatenations, a StringBuilder is more efficient.
Q10. What happens when I assign one array to another?
Only the reference is copied, so both variables point to the same array. Use clone() or Arrays.copyOf() to create a separate copy.
Q11. What is the difference between x =+ 5 and x += 5?
x =+ 5 is read as x = +5, which simply assigns 5. x += 5 adds 5 to the current value. The first is a common typo.
Q12. Can compound assignment cause overflow?
Yes. Because of the implicit cast, byte b = 120; b += 10; silently wraps to -126. No error or warning is produced.
Q13. Can I use assignment operators with final variables?
Only for the single initial assignment. Any later assignment, including compound assignments, to a final variable is a compile error.
Q14. Is if (x = 5) valid in Java?
Not for an int: the condition must be a boolean, so it fails to compile. For a boolean variable, if (flag = true) compiles but always assigns and evaluates to true, a classic bug.
Q15. What does %= do?
It replaces the variable with the remainder of dividing it by the right operand: x %= 7 is x = x % 7.
Q16. What does <<= do?
It shifts the bits of the variable left by the given number of positions and stores the result: x <<= 2 multiplies a positive int by 4.
Q17. Is there a ++= or **= operator in Java?
No. Java has ++ for incrementing by one, but no ++=, and no power operator at all; use Math.pow().
Q18. Is assignment thread-safe?
Assigning a single int or reference is atomic, but compound operations like count += 1 are read-modify-write and not atomic. Use AtomicInteger or synchronization for shared counters.
Q19. Can += be used on a char?
Yes. char c = 'A'; c += 2; makes c equal to 'C', thanks to the implicit cast.
Q20. Does Java evaluate the left variable once in x[i++] += 1?
Yes. In a compound assignment the left-hand expression is evaluated only once, so i is incremented once. With x[i++] = x[i++] + 1 it would be incremented twice.