This program increments a variable repeatedly and then prints its value. What is it?
public class Increment {
public static void main(String[] args) {
j = 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:
Fixing the program is as simple as removing the extraneous assignment from the loop, leaving:
for (int i = 0; i < 100; i++)
No comments:
Post a Comment