Increment & decrement in Java
Prefix ++x vs postfix x++ and the classic x = x++ trap.
x = 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--; // 3Prefix 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 = 5Your turn
What does this print?
int n = 10;
int m = n++;
System.out.println(n);
System.out.println(m);11 1011 1110 10
Show the answer
m gets the old value 10, and n is bumped to 11.
Your turn
What does this print?
int k = 3;
int r = ++k * 10;
System.out.println(r);304031
Show the answer
Prefix: k becomes 4 first, and the expression's value is 4. So r = 4 * 10 = 40.
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 = 4In 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
- ++x: increment, then use the new value
- x++: use the old value, then increment
- x = x++; leaves x unchanged!
- Avoid using the same variable twice with ++ in one expression
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);- 6 6
- 5 5
- 6 5
- 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);- 10
- 11
- 12
- 6
Check your answer
12. Prefix ++ increments x to 6 first, and the expression's value is 6, so y = 6 * 2 = 12.