Post Increment Operator in Java
The Java post increment operator ( ) is often a source of confusion for programmers due to its unique behavior. In this article, we will explore the intricacies of the post increment operator and address why the following code snippet from "Java Puzzlers" by Joshua Bloch produces unexpected results:
<code class="java">public class Test22 { public static void main(String[] args) { int j = 0; for (int i = 0; i < 100; i++) { j = j++; } System.out.println(j); // prints 0 int a = 0, b = 0; a = b++; System.out.println(a); System.out.println(b); // prints 1 } }</code>
Based on the author's explanation, the expression j = j should behave similar to the following:
<code class="java">temp = j; j = j + 1; j = temp;</code>
This logic implies that the value of j should increment and then be assigned to j, resulting in an increment similar to the expression a = b . However, in the latter case, the post increment operator is used in a different context, leading to a different outcome.
The correct evaluation of a = b is actually as follows:
<code class="java">temp = b; b = b + 1; // increment a = temp; // then assign</code>
This is consistent with the Java Language Specification (JLS), which states that for postfix increment expressions, "the value 1 is added to the value of the variable and the sum is stored back into the variable." Therefore, a = b assigns the original value of b (0) to a before incrementing b to 1.
Returning to the expression j = j , we can now see that the post increment operator causes j to be evaluated before the increment, resulting in a constant assignment of 0. The temp variable added in the author's explanation is not actually involved in the post increment evaluation.
By understanding the true behavior of the post increment operator, we can avoid confusion and ensure accurate code execution.
The above is the detailed content of Why does `j = j ` result in 0 in Java, but `a = b ` increments `b` to 1?. For more information, please follow other related articles on the PHP Chinese website!