-2

I have this code...

for(int i=0; i<10 ; ) {
    i = i++;
    System.out.println("Hello World");
}

Output:

Hello World
Hello World
Hello World...

The loop will repeat infinitely, because i remains 0 after every iteration of the loop.

I thought this expression i = i++; was redundant... like this one i=(i=i+1);, but it remains 0 so how does it work?

Luisk4
  • 377
  • 1
  • 5
  • 12

1 Answers1

0

i = i++; is a tricky construct, what it really does is something like the following:

int iOld = i;
i = i + 1;
i = iOld;

First, the value of i is pushed on a stack. Then, the variable i is incremented. Finally, the value on top the stack is popped off and assigned into i. The net result is that nothing happens -- a smart optimizer could remove the whole statement.

Anurag Sharma
  • 2,409
  • 2
  • 16
  • 34