I saw this code in a book. The condition is true so why the result of this loop is 0?
boolean a = false;
for (int i = 0; a = !a ;) {
System.out.println(i++);
}
I saw this code in a book. The condition is true so why the result of this loop is 0?
boolean a = false;
for (int i = 0; a = !a ;) {
System.out.println(i++);
}
You're looping until a = !a
returns false, at which point the loop will break. This will happen on the second iteration (when i
is equal to 1), as a
will switch back to false
.
First iteration:
i
is equal to 0
, a = !a
is evaluated which changes the value of a
to true, hence the loop body executes. The value of i
(zero) is printed and then incremented to 1 (this is a post-increment).
Second iteration:
i
is equal to 1
, a = !a
is evaluated which changes the value of a
to false, hence the loop breaks.
It works this way:
You execute a = !a
it returns true
you can test manually:
System.out.println(a = !a);
Condition is true, so you execute loop body:
System.out.println(i++);
i++
is a postfix increment
, so it first returns i
value, which is 0
, after that increase it.
That's why the output of the program is 0
. If you try to print i
after the loop, the output will be 1
.