2

I have simple question. Why result of this loop is 12? I thought it will be 11...

public static void main(String[] args) {
    int i = 10;

    while (i++ <= 10){
    }

    System.out.println(i);
}


//RESULT: 12
asss
  • 153
  • 1
  • 1
  • 4

4 Answers4

7

It will run the conditions in the while-loop twice, first time when i = 10, then it will increment it to 11. Then it will check if i <= 10 again, and it will be false, but it will still increment i resulting in it becoming 12.

ddmps
  • 4,350
  • 1
  • 19
  • 34
2

This happens because it must do another check before exiting the loop.

i is 10
check i++<=10?
i is 11
check i++<10?
exit
i is 12
Lemur
  • 2,659
  • 4
  • 26
  • 41
Trevor Baron
  • 370
  • 2
  • 8
1

i++ says "give me the current value of i, then increment it". In this case, when i = 10 it's incremented to 11 then the the expression is true for the previous value 10, so the loop repeats, does the test for i = 11, increments i to 12, and the expression is now false, stopping the loop.

This post-increment behavior is somewhat confusing and therefore should only be used when it's exactly what you need. In general, it's much better to pretend ++ doesn't return anything, this will generally make the intent of your code much more clear:

while(i <= 10) {
    i++;
}
dimo414
  • 47,227
  • 18
  • 148
  • 244
1
Iteration 1 : i=10
condition true  ===>>> while loop executed once
i incremented to 11


iteration 2 : i=11
condition false ===>>> while loop exited
but after exiting the while loop
i is incremented again to ===>>> i =12

and that is what you get as output