Assignment Operators in Java
Beyond plain =, Java has compound assignment operators that combine an operation with assignment in one step: +=, -=, *=, /=, and %= each apply the operator to the variable's current value and store the result back into that same variable. x += 5 means exactly the same thing as x = x + 5, just shorter to write — and, for some types, subtly different underneath.
On a narrower type like byte or short, compound assignment includes an implicit narrowing cast that plain arithmetic wouldn't get. byteVar += 1 compiles cleanly even though byteVar = byteVar + 1 would not, since the right side of that second version promotes to int and can't be assigned back to byte without an explicit cast.
Plain assignment
= stores the value on the right into the variable on the left.
Compound arithmetic assignment
+=, -=, *=, /=, %= each combine an operation with storing the result back into the same variable.
Compound assignment is shorthand
x += 5 does exactly what x = x + 5 does, just more compactly.
A hidden implicit cast
On a narrower type like byte or short, a compound assignment operator includes an implicit narrowing cast that writing the expanded form out by hand would not get automatically.
Compound bitwise assignment exists too
&=, |=, ^=, <<=, >>=, and >>>= apply the matching bitwise operator the same shorthand way.
public class AssignmentDemo { public static void main(String[] args) { int total = 10; total += 5; total *= 2; System.out.println("Total: " + total); byte small = 10; small += 1; System.out.println("Small: " + small); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.