Advertisement
Intermediate Java, Java Fundamentals: Syntax, Data Types & Operators

What is the difference between the ++ (increment) and -- (decrement) operators used in prefix versus postfix position, and what subtle bug can arise from using them within a complex expression?

Short answer

The prefix form (++x) increments the variable FIRST, then evaluates to the NEW, already-incremented value; the postfix form (x++) evaluates to the ORIGINAL, pre-increment value FIRST, then increments the variable afterward -- using either form within a larger, complex expression…

Save Java mock interview
Advertisement
AModel answer
The prefix form (++x) increments the variable FIRST, then evaluates to the NEW, already-incremented value; the postfix form (x++) evaluates to the ORIGINAL, pre-increment value FIRST, then increments the variable afterward -- using either form within a larger, complex expression that also references the same variable elsewhere (like `int result = x++ + x++;` or worse, combining pre/post-increment of the same variable with an assignment to that same variable in one statement) can produce genuinely confusing, easy-to-misjudge results, and is generally considered poor practice specifically because the exact evaluation order and timing, while technically well-defined by the language specification, is difficult for most readers (and even experienced developers) to correctly reason about at a glance.
int x = 5;
int a = x++;  // a = 5 (original value), x becomes 6 afterward

int y = 5;
int b = ++y;  // y becomes 6 FIRST, b = 6 (the new, incremented value)

// Confusing, discouraged: mixing multiple increments of the SAME variable in one expression
int z = 1;
int confusing = z++ + ++z;  // technically well-defined (results in 1 + 3 = 4), but genuinely hard to read correctly
Real-world example
A code review flags a statement combining both prefix and postfix increment of the same variable within a single complex expression as a readability hazard, recommending it be split into multiple separate, clearer statements even though the original code was technically correct according to Java's well-defined evaluation order rules.
Likely follow-ups
  • Why does the Java Language Specification define such precise evaluation order rules for these operators if using them this way is discouraged anyway?
  • Is there ever a genuinely good, readable reason to prefer prefix over postfix increment (or vice versa) in ordinary, non-confusing code?
Related topics