Home >Java >javaTutorial >Why Does `j = j ` Result in `j` Remaining 0 in Java?

Why Does `j = j ` Result in `j` Remaining 0 in Java?

DDD
DDDOriginal
2024-10-26 23:43:30706browse

Why Does `j = j  ` Result in `j` Remaining 0 in Java?

Post Increment Operator in Java

In Java, the post increment operator ( ) increments the value of a variable by one after its evaluation. This behavior can lead to unexpected results, as exemplified by the code provided in "Java Puzzlers":

<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>

The confusion arises when examining the statement j = j . According to the Java Language Specification (JLS), this statement is equivalent to:

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

However, this explanation contradicts the result of a = b , which assigns 0 to a and increments b to 1. To resolve this discrepancy, it's crucial to note that a = b is evaluated as follows:

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

This means that post increment assignments of the form lhs = rhs are equivalent to:

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

Applying this rule to both j = j and a = b clarifies the results observed in the code. j = j effectively assigns the value of j (0) to temp, increments j to 1, and then assigns temp (0) back to j. This explains why j prints 0 despite the increment operator.

The above is the detailed content of Why Does `j = j ` Result in `j` Remaining 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