Home  >  Article  >  Java  >  Why Does `j = j ` Result in `j` Staying at 0 in Java?

Why Does `j = j ` Result in `j` Staying at 0 in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 21:35:03430browse

Why Does `j = j  ` Result in `j` Staying at 0 in Java?

Post Increment Operator in Java

The following code snippet from Joshua Bloch's "Java Puzzlers" seems puzzling at first glance:

<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); // prints 0
        System.out.println(b); // prints 1
    }
}</code>

Confusion Over Post Increment

The confusing part is the behavior of j = j , which results in j remaining at 0. According to the author, this expression is similar to:

<code class="java">temp = j;
j = j + 1;
j = temp;</code>

However, in the case of a = b , b indeed becomes 1, which seems inconsistent.

Understanding the Difference

To resolve this confusion, we need to understand the rule for postfix increment operator ( ):

lhs = rhs++;

Is equivalent to:

temp = rhs;
rhs = rhs + 1;
lhs = temp;

Applying the Rule

Applying this rule to a = b , it becomes:

temp = b;
b = b + 1;
a = temp;

Hence, a gets the original value of b (which is 0), and b is then incremented to 1.

In the Case of j = j

Similarly, applying the rule to j = j yields:

temp = j;
j = j + 1;
j = temp;

Since temp is equal to the original value of j (which is 0), j is incremented to 1 but then immediately overwritten with the original value (0), resulting in j remaining at 0.

Conclusion

The key to understanding the behavior of post increment operator is to remember the rule that lhs = rhs is a two-step process: first, the current value of rhs is assigned to temp, then rhs is incremented, and finally temp is assigned to lhs.

The above is the detailed content of Why Does `j = j ` Result in `j` Staying at 0 in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn