Card 07/ 09

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.

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

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

i++ 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.

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.