Card 07/ 09
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:
int i = 5;
int j = i++;
System.out.println(i + " " + j);6 5The 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.
| Written | The expression produces | i afterwards |
|---|---|---|
i++ | The value before the increase | One higher |
++i | The value after the increase | One 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.
← → move through sections and cards