What is happening happens because java is pass-by-value.
In the first loop, i
is getting incremented in the i++
statement, however, in the second loop what is happening is that i
gets pointed to a new memory location that stores the value of i
(in this case 0) and then increments the old location.
To visualise:
i => 0x00000001 // 0
for() {
i => 0x00000002 <- 0 // store old i value (0) in new location
0x00000001++ // Increment the value stored at the old location
// Cause there is no longer a reference to 0x00000001,
// it will get garbage collected and you will be left with
// i => 0x00000002
And it will keep doing that, assigning the old value to a new location and incrementing the old value for each pass of the loop