Skip to content
Tutorials Center
My learning

Topics

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.

Java
int total = 10;
total += 5;       // 15
total <<= 2;      // 60

Try it

Java Compound operators and the implicit cast

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.

Java Assignment as an expression

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

Java
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= y evaluates as x = (T)(x op y), where T is the type of x. This silently truncates, as in i += 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 = 7 assigns c first.
  • Strings. s += x is allowed for String and builds a new string each time. In loops use StringBuilder.
  • Definite assignment. A local variable must be assigned before it is read. Fields get default values.
  • final variables 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. Writing if (x = true) for a boolean compiles and is almost always a typo for ==.
  • Reference assignment copies the reference, not the object. Two variables then point at the same object.