Java Reference ยท Operators
Java assignment operators
Reference for Java assignment operators: simple assignment, compound operators such as += and <<=, the implicit cast, and assignment as an expression.
The assignment operator = stores a value in a variable, a field or an array element. Java also has compound assignment operators that combine an operation with the store: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>= and >>>=.
Assignment is an expression: it has the value that was stored, so a = b = 0 works and assigns right to left. A compound assignment is not just shorthand for x = x + y. It also casts the result back to the type of the left-hand side, which is why it compiles in cases where the long form does not.
int total = 10; total += 5; // 15 total <<= 2; // 60
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
variable = expression;
variable op= expression; // same as variable = (T)(variable op expression)
| Operator | Meaning |
|---|---|
= |
Store the value |
+= -= *= /= %= |
Arithmetic, then store |
&= |= ^= |
Bitwise or logical (on boolean), then store |
<<= >>= >>>= |
Shift, then store |
There is no &&= or ||= in Java.
Usage notes
- Implicit narrowing.
x op= yevaluates asx = (T)(x op y), whereTis the type ofx. This silently truncates, as ini += 3.9. If you want the compiler to object, write the long form. - The left operand is evaluated once. In
arr[next()] += 1,next()runs a single time. - Right-associative.
a = b = c = 7assignscfirst. - Strings.
s += xis allowed forStringand builds a new string each time. In loops useStringBuilder. - Definite assignment. A local variable must be assigned before it is read. Fields get default values.
finalvariables can be assigned once; any compound operator on them is a compile error.- Assigning inside a condition (
while ((line = r.readLine()) != null)) is a legal idiom. Writingif (x = true)for abooleancompiles and is almost always a typo for==. - Reference assignment copies the reference, not the object. Two variables then point at the same object.