Card 07/ 09

GotchaDifficulty: Intermediate1 min

i++ vs ++i: Why j Is 5 After int j = i++

An index always one behind, and a line that looks like it increments before it assigns.

i++ and ++i both add one to i, and differ in the value they produce. i++ produces the old value and then increases i; ++i increases i and then produces the new value. The difference only shows when something uses that value.

The symptom is an index that is always one behind, or an array write that lands in the wrong slot. The line looks like it increments and then assigns:

java
int i = 5;
int j = i++;

System.out.println(i + " " + j);
text
6 5

The value the expression i++ produced, five, is what gets assigned to j. i is six by the time the next line runs.

++i is the same two things in the other order: increase first, then produce the new value. int j = ++i; leaves both at six.

What each form produces and what it leaves behind
WrittenThe expression producesi afterwards
i++The value before the increaseOne higher
++iThe value after the increaseOne higher

On a line of its own the two are identical, which is why for (int i = 0; i < n; i++) never causes trouble. The difference only exists when something uses the value, so keep the increment on its own line whenever you can.