Issue
I started learning java and came across this following code, and I was expecting it to print the numbers 1 - 9, however; it's going in an infinite loop. I was wondering why that is happening.
while (i<10) {
System.out.println(i);
i = i++;
}
However, when I do this, it prints just fine:
while (i<10) {
System.out.println(i++);
}
Solution
The statement i++
increments i
by 1
, returning the previous value.
This means that in the first loop, you are infinitely increasing i
by 1
and then setting it back to its previous value, meaning it never changes.
However, in the second loop, you are not setting i
back to its previous value, allowing it to increase and the loop to end.
To fix the first loop, change the third line from:
i = i++;
to:
i++;
Identical behaviour can also be achieved through a for loop:
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
The first statement inside the brackets is what should be run first, in this case defining i
as a int
with a value of 0
. The next statement is the conditional that is checked before each iteration. In this example, it checks if i
is less than 10
. The third and final statement is the code to run at the end of each iteration. In this example, i++
is run, increase the value of i
by 1
each iteration.
Answered By - KingsMMA
Answer Checked By - Timothy Miller (JavaFixing Admin)