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

Prefix vs Postfix: Evaluation Order

Understand the critical difference between ++i (prefix) and i++ (postfix) and when each evaluates.

Prefix vs Postfix: Evaluation Order

What you'll learn: You'll discover exactly when ++i and i++ change the variable's value and how that timing affects your expressions.

The Critical Timing Difference

Both ++i (prefix) and i++ (postfix) add 1 to your variable, but they differ in when that increment happens relative to using the value in an expression:

  • Prefix (++i): Increment first, then use the new value
  • Postfix (i++): Use the current value first, then increment

Think of it like getting coffee: prefix is "fill the cup, then drink it," while postfix is "drink what's there, then refill."

How It Works in Practice

When you write int result = ++i;, Java increments i immediately, then assigns the new value to result. Both variables end up with the incremented value.

When you write int result = i++;, Java assigns the current value of i to result first, then increments i. So result gets the old value, while i gets the new value.

Standalone vs Expressions

When used alone on their own line, there's no practical difference:

i++;  // Just increments i
++i;  // Also just increments i (same effect)

But in assignments or larger expressions, the timing matters dramatically:

int x = 5;
int a = x++;  // a is 5, x is now 6
int b = ++x;  // b is 7, x is now 7

Key Takeaway: Prefix (++i) increments before the value is used; postfix (i++) uses the value first, then increments. This evaluation order only matters when the operator appears within a larger expression.