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

Basically the value of i remains unchanged, and stays 0, so it is infinite. But Why doesnt it change?

If I changed i=i++ to i++, it works. (not infinite loop).

Vince
  • 14,470
  • 7
  • 39
  • 84

2 Answers2

6

Because i++ increments i after the expression is evaluated so you are basically saying i = i. If you do i = ++i then it will work because it increments i before the expression is evaluated.

trincot
  • 317,000
  • 35
  • 244
  • 286
brso05
  • 13,142
  • 2
  • 21
  • 40
0

Logically, the assignment is done after evaluation of the right hand side, as for any other Java assigment. However, "The value of the postfix increment expression is the value of the variable before the new value is stored." (JLS, 15.14.2. Postfix Increment Operator ++)

The value of i before the incremented value is stored stays zero, because of the assignment.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75