1

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++);
}
alvira
  • 147
  • 1
  • 7

2 Answers2

2

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.

M A
  • 71,713
  • 13
  • 134
  • 174
2

It works this way:

  1. You execute a = !a it returns true you can test manually:

    System.out.println(a = !a);
    
  2. 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.

vszholobov
  • 2,133
  • 1
  • 8
  • 23