➗ Operators & Expressions · Beginner

Increment & decrement in Java

Prefix ++x vs postfix x++ and the classic x = x++ trap.

🧩 The mysteryx = x++; looks like it adds one to x. Run it and x hasn't changed at all. Where did the increment go?

Shortcuts for +1 and -1

x++ adds one to x and x-- subtracts one. On a line of their own, they're the same as x = x + 1 and x = x - 1.

int lives = 3;
lives++;   // 4
lives--;   // 3

Prefix vs postfix

Inside a bigger expression they differ. Prefix ++x: increment first, and the expression's value is the new x. Postfix x++: the expression's value is the old x, and x changes as a side effect.

int x = 5;
int a = ++x;  // x = 6, a = 6
int y = 5;
int b = y++;  // y = 6, b = 5
🔮 Predict it

Your turn

What does this print?

int n = 10;
int m = n++;
System.out.println(n);
System.out.println(m);
  1. 11 10
  2. 11 11
  3. 10 10
Show the answer

m gets the old value 10, and n is bumped to 11.

🔮 Predict it

Your turn

What does this print?

int k = 3;
int r = ++k * 10;
System.out.println(r);
  1. 30
  2. 40
  3. 31
Show the answer

Prefix: k becomes 4 first, and the expression's value is 4. So r = 4 * 10 = 40.

⚠️ The trap

x = x++

x++ evaluates to 5 and bumps x to 6. Then the assignment runs last and stores that old 5 back into x, overwriting the 6. To increment, just write x++;.

int x = 5;
x = x++;
System.out.println(x);  // 5!

Left to right, always

Java evaluates operands left to right, so even puzzles have a definite answer. Still, avoid using the same variable twice with ++ in one expression: it's a riddle, not code.

int i = 1;
int r = i++ + ++i;
// i++ gives 1 (i is now 2)
// ++i makes i 3 and gives 3
// r = 1 + 3 = 4
💼 In the real world

In real projects

In real code, ++ mostly lives in loops (i++) and in counters on their own line, where prefix and postfix behave the same. Interviewers love x = x++ puzzles; code reviewers reject them.

Key takeaways

  1. ++x: increment, then use the new value
  2. x++: use the old value, then increment
  3. x = x++; leaves x unchanged!
  4. Avoid using the same variable twice with ++ in one expression
🤯 Did you know?

Java borrowed ++ from C, and the name C++ is a programmer's joke: "C, incremented by one".

Practice questions

What does this print?

int x = 5;
int y = x++;
System.out.println(x + " " + y);
  1. 6 6
  2. 5 5
  3. 6 5
  4. 5 6
Check your answer

6 5. y gets the old value 5, and x is incremented to 6.

What does this print?

int x = 5;
int y = ++x * 2;
System.out.println(y);
  1. 10
  2. 11
  3. 12
  4. 6
Check your answer

12. Prefix ++ increments x to 6 first, and the expression's value is 6, so y = 6 * 2 = 12.

Next: b += 1 compiles for a byte, but b = b + 1 doesn't. Compound assignment hides a cast.