Thursday, October 28, 2010

Loopy Problem - I

This program increments a variable repeatedly and then prints its value. What is it?

public class Increment {

public static void main(String[] args) {

int j = 0;

for (int i = 0; i < 100; i++)

j = j++;

System.out.println(j);

}

}

At first glance, the program might appear to print 100. After all, it does increment j 100 times. Perhaps surprisingly, it does not print 100 but 0. All that incrementing gets us nowhere. Why?

When placed after a variable, the ++ operator functions as the postfix increment operator [JLS 15.14.2]: The value of the expression j++ is the original value of j before it was incremented. Therefore, the preceding assignment first saves the value of j, then sets j to its value plus 1, and, finally, resets j back to its original value. In other words, the assignment is equivalent to this sequence of statements:

int tmp = j;

j = j + 1;

j = tmp;

The program repeats this process 100 times, after which the value of j is exactly what it was before the loop, or 0.

Fixing the program is as simple as removing the extraneous assignment from the loop, leaving:

for (int i = 0; i < 100; i++)

j++;

No comments:

Post a Comment