0

Given is the following code:

public class tester {

public static void main(String args[]) {

    int a = 0;
    while(a == a++) {
        a++;
        System.out.println(a);
    }
}

}

My question is, why would this print out all even numbers, starting from 2?

Why does it even go through the while loop? The condition in the very beginning: if a is equal to a+1: but 0 is not equal to 1.

That's at least my thoughts on this. Any proper answer?

javascaped
  • 31
  • 5

1 Answers1

4

You must consider what a++ does - first it returns the value of a to be used in the calculation. Then it increments a. So a == a++ is ALWAYS true. By comparison, a == ++a which does the increment before it returns the value to be used in the calculation, is NEVER true.

From there, you then increment a again. So each loop it's being incremented twice, which is why you see even numbers and never odd.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
  • Consider `while(condition) { execute; }` the condition is always evaluated, but the execute is not always evaluated. If you want to guarantee one execution, you need to say [`do { execute; } while (condition);`](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html) – corsiKa Jun 07 '18 at 19:37