Card 07/ 09
All 9 cards
GotchaDifficulty: Intermediate1 min
Why j Is 5 After int j = i++
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 5i++ does two things in a fixed order: it produces the old value of i, and then it increases i. The value the expression produced — five — is what gets assigned. 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.