Home > Java > javaTutorial > body text

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

Linda Hamilton
Release: 2024-10-26 21:35:03
Original
439 people have browsed it

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>
Copy after login

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>
Copy after login

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++;
Copy after login

Is equivalent to:

temp = rhs;
rhs = rhs + 1;
lhs = temp;
Copy after login

Applying the Rule

Applying this rule to a = b , it becomes:

temp = b;
b = b + 1;
a = temp;
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!