Course contentsShow
← Java
Lesson 100 of 2,8703. Operators and ExpressionsFree lesson

Common Pitfalls with Postfix Operators

Learn why expressions like 'x = x++' produce unexpected results and how to avoid these mistakes.

Common Pitfalls with Postfix Operators

You'll learn why certain expressions using postfix ++ and -- produce confusing results and how to write clearer code.

The Trap of Self-Assignment

When you combine the postfix increment operator with assignment to the same variable, things get messy. Consider this expression:

int x = 5;
x = x++;
System.out.println(x);  // Prints 5, not 6!

Wait, what? Despite the ++, x remains 5. Here's why:

The postfix x++ returns the original value of x (which is 5) before incrementing. So the expression evaluates like this:

  1. The old value (5) is remembered for the expression result
  2. x gets incremented to 6
  3. Then the assignment x = ... stores that old value (5) back into x
  4. The increment is overwritten!

The Fix: Don't Mix Assignment and Side Effects

This isn't a useful pattern—it's just confusing. If you want to increment x, simply write:

x++;  // Clear and correct

Or if you need the old value:

int oldValue = x;
x++;

Key Takeaway: Avoid expressions like x = x++ or x = x--. The assignment overwrites the increment/decrement, creating confusion. Keep increment/decrement operations on their own line for clarity and predictability.