Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 201 ยท Operators

Assignment and Increment Operators

Learn Java's = and compound assignment operators, the hidden cast inside +=, prefix vs postfix ++ and --, and the classic puzzles that trip up developers.

Almost every line of a real program changes a variable: a total grows, a counter ticks, a balance drops. Java gives you a small family of operators for that job. The plain = stores a value, compound assignment operators such as += update a variable in place, and the increment and decrement operators ++ and -- add or subtract one.

They look simple, and most of the time they are. But each one hides a detail that surprises even experienced developers: = is an expression with a value, += contains an invisible cast, and x++ and ++x give different results. This lesson covers all of it, ending with the puzzles that show up in interviews and code reviews.

The simple assignment operator =

= takes the value on its right and stores it in the variable on its left. The left side must be something that can hold a value: a variable, a field or an array element. You can't assign to a literal or to the result of a calculation.

Java
int score = 10;      // declaration with an initializer
score = 25;          // assignment: replaces 10 with 25
int[] points = new int[3];
points[0] = score;   // array elements are assignable too
// 10 = score;       // compile error: 10 is not a variable
// (score + 1) = 5;  // compile error: a sum is not a variable

The value must be compatible with the variable's type. You can store an int in a long (a widening conversion, covered in Type Casting and Conversion), but storing a double in an int needs an explicit cast.

= means store, not is equal to. To compare two values you use ==, which you will meet in Comparison and Logical Operators.

Assignment is an expression

In Java, an assignment does two things: it stores the value, and it produces the value it stored. That means you can use an assignment inside a bigger expression. The most common use is chaining:

Java Assignment produces a value

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.

= is right-associative, so a = b = c = 7 is read as a = (b = (c = 7)). The innermost assignment runs first, and its value flows outward.

You will also see assignment inside a loop condition, a classic pattern for reading data until there is none left:

Java
String line;
while ((line = reader.readLine()) != null) {
    process(line);
}

The parentheses matter: they make the assignment happen first, and then its value is compared with null. This idiom is fine because it is common and well known. Outside of it, keep assignments as separate statements; int y = (x = 4) * 10; is legal but hard to read.

The if (x = 5) mistake

In C, writing = instead of == in a condition is a famous bug. Java blocks most of it: a condition must be a boolean, and x = 5 produces an int, so if (x = 5) does not compile. There is one case Java can't catch:

Java
boolean done = false;
if (done = true) {        // compiles! assigns true, then tests it
    IO.println("Always runs");
}

The fix is simple: never compare a boolean with true or false. Write if (done) or if (!done) instead, and the mistake can't happen.

Compound assignment operators

Updating a variable based on its current value is so common that Java has a shortcut for every binary arithmetic and bitwise operator:

Operator Example Means roughly
+= total += price total = total + price
-= stock -= sold stock = stock - sold
*= area *= 2 area = area * 2
/= half /= 2 half = half / 2
%= index %= size index = index % size
&= |= ^= flags |= READ flags = flags | READ
<<= >>= >>>= bits <<= 1 bits = bits << 1

The bitwise and shift versions are explained in Bitwise and Shift Operators. Arithmetic ones behave exactly like the operators from Arithmetic Operators: /= on an int still does integer division, and += on a String still concatenates.

Java Compound assignment in action

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.

The hidden cast inside +=

Here is the detail that makes compound assignment more than a shortcut. The Java Language Specification defines x op= y as

TEXT
x = (T) ((x) op (y))

where T is the type of x. There is a cast back to the variable's type, and you never see it. With int and int it makes no difference, but with smaller or mixed types it changes what compiles and what you get:

Java The implicit narrowing 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.

The first line explains why many people believe b += 5 and b = b + 5 are the same: they usually are. But arithmetic on byte, short and char always promotes the operands to int (see numeric promotion), so b + 5 is an int and can't be stored back in a byte without a cast. += adds the cast for you.

That convenience is also a trap. whole += 2.7 compiles and quietly throws away the fraction, and small *= 300 overflows to 24464 with no error at all. When the right side could be bigger or more precise than the variable, write the full form with an explicit cast, or use a wider type, so the loss is visible to the reader.

Compound assignment never checks for overflow. int count = Integer.MAX_VALUE; count += 1; silently becomes -2147483648. If overflow would be a bug, use Math.addExact(count, 1), which throws an exception instead. Working with Numbers covers this in detail.

The left side is evaluated only once

The other difference between x op= y and x = x op y is that x itself is evaluated once. That matters when the left side has a side effect, such as an array index that moves:

Java
int[] counts = {0, 0, 0};
int i = 0;
counts[i++] += 10;               // updates counts[0], then i is 1
// counts[i++] = counts[i++] + 10;  // reads and writes DIFFERENT elements

With +=, the element is located once, read, updated and written back. The long form would run i++ twice and touch two different slots, which is almost never what you meant.

Increment and decrement: ++ and --

Adding or subtracting one is the most common update of all, so it has its own operators. ++ adds 1 to a variable and -- subtracts 1. Each comes in two forms:

  • Prefix, ++x: increments first, then the expression's value is the new value.
  • Postfix, x++: the expression's value is the old value, and the increment happens as part of evaluating it.

When ++ or -- is a statement on its own, the two forms do exactly the same thing. The difference only shows when you use the result:

Java Prefix vs postfix

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.

A useful way to remember it: read the code left to right. In a++ you see a first, so you get a's value, then the ++. In ++c you see ++ first, so the increment happens before you read c.

++ and -- work on every numeric type, including char, long and double, and they include the same hidden cast as +=. Incrementing a byte holding 127 wraps to -128. char is especially handy:

Java
for (char ch = 'a'; ch <= 'e'; ch++) {
    IO.print(ch);   // abcde
}

You can only increment a variable. 5++, (a + b)++ and ++ on a final variable are compile errors, and so is ++x++, because x++ produces a value, not a variable.

Where ++ belongs

The classic home for ++ is the update part of a for loop, covered in for Loops: for (int i = 0; i < n; i++). Prefix and postfix are equally fast there; modern compilers produce the same bytecode when the value isn't used. Most Java code uses i++ by convention.

Using the value of ++ inside a larger expression is legal and sometimes neat, for example items[size++] = item; appends to an array and bumps the size in one step. Keep it to idioms like that. As soon as a variable is incremented and read elsewhere in the same expression, readers have to slow down, which brings us to the puzzles.

Puzzles: what really happens

Java defines evaluation order precisely: operands are evaluated left to right, and each side effect happens at a fixed moment. (In C and C++ some of these expressions are undefined behavior; in Java they always give the same answer.) That makes them good puzzles. Predict each line before you press Run.

Java Increment puzzles

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.

Here is how each one works:

  1. x = x++ leaves x at 5. The right side is evaluated first: its value is the old x (5), and as a side effect x becomes 6. Then the assignment stores 5 back into x, overwriting the 6.
  2. i++ + ++i is 12, and i ends at 7. Left to right: i++ gives 5 and makes i 6; then ++i makes i 7 and gives 7. So 5 + 7 = 12.
  3. k += k++ gives 2. The left k is read first (1), then k++ gives 1 (and sets k to 2), then the sum 1 + 1 = 2 is stored, overwriting the increment.
  4. s += 1 + 2 prints Total: 3. The whole right side is evaluated first, as (1 + 2), so it adds 3. Compare with s = s + 1 + 2, which gives Total: 12, because that one concatenates left to right.
  5. count = count++ never changes count. It is puzzle 1 inside a loop, and a real bug pattern: the intent was count++.

The lesson from these puzzles is not to memorize them, but to avoid writing them. Use ++ and -- as standalone statements or in well-known idioms, and never read and modify the same variable twice in one expression. Static analysis tools such as SpotBugs and IntelliJ's inspections flag x = x++ for exactly this reason.

Assignment and types: a quick reference

A few more rules round out the picture:

  • Declarations aren't expressions. int a = 1, b = 2; declares two variables, but int a = int b = 2; is a compile error. Chained assignment works only on variables that already exist.
  • final variables can be assigned once. After that, =, += and ++ are all compile errors. See Constants and final.
  • var takes the type of its first value. var total = 0; makes an int, so a later total += 0.5; silently truncates thanks to the hidden cast. Write var total = 0.0; if you need decimals. More in Local Variable Type Inference with var.
  • Reference assignment copies the reference, not the object. After int[] copy = original;, both names point to the same array. You will see why in Arrays.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int a = 4; int b = a++ * 2; IO.println(a + " " + b);

    The postfix a++ produces the old value 4, so b = 4 * 2 = 8. The side effect still makes a 5.
  2. 2. Given byte b = 100;, which line compiles?

    b + 1 is an int, so storing it in a byte needs a cast. b += 1 includes that cast automatically: it means b = (byte) (b + 1).
  3. 3. What is the value of n after int n = 7; n += 0.9;?

    The hidden cast turns n + 0.9 (7.9) back into an int, and casting to int truncates toward zero, so n stays 7.
  4. 4. What is printed? int x = 3; x = x++; IO.println(x);

    The right side evaluates to the old value 3 and increments x to 4, then the assignment stores 3 back. Java defines this order exactly, so the result is always 3.
  5. 5. What does String s = "v"; s += 2 + 3; IO.println(s); print?

    s += 2 + 3 means s = s + (2 + 3). The right side is computed first as the number 5, then appended.

Summary

  • = stores a value and also produces it, which allows chains like a = b = 0 and the while ((line = ...) != null) idiom.
  • Compound operators (+=, -=, *=, /=, %= and the bitwise ones) update a variable in place. x op= y means x = (T) (x op y): it contains a hidden narrowing cast and evaluates x only once.
  • That cast lets byte += int compile, but it also silently truncates decimals and lets values overflow.
  • ++x increments and then gives the new value; x++ gives the old value and then increments. As standalone statements they are identical.
  • Java evaluates operands left to right, so puzzles like x = x++ have a defined answer, but code that reads and modifies the same variable in one expression should be rewritten.

Next: Comparison and Logical Operators, where you will build conditions with ==, <, && and || and learn how short-circuiting works.