java – Why doesn't x = x ++ increase the value of x in the loop?

Question:

int x = 0;
while (x < 3) {
    x = x++;
    System.out.print(x + " ");
}

I understand that if y = x++ is written, then first y assigned the value of х , after which х increased by one. Why doesn't this happen with the expression х = х++ ?

Answer:

x = x++;

equivalent to

int tmp = x;
x++;
x = tmp;

First, the old value is assigned, the increment is done, the old value is assigned – therefore, the loop is infinite, x = 0 always.

Scroll to Top