The difference between i = i++ and j = i++ in Java

Source: Internet
Author: User

Since the use of i++ and i--will result in a change in value, the Java compiler will re-allocate a new memory space for the variable to store the original value when the Post + + and--is processed.

When the assignment is completed, the memory is freed.

(1) for J = i++ case

The original value of i is stored in the post-open memory, finally, this value is assigned to J, j = i++ operation, J will get the value of I, and I will be added, so, after releasing the memory, the original storage of J and I will get the values are: J (at this time the value is equal to the initial I value) and I (I self-added value).

public static void Main (String args[]) {int J = 0;int k = 0;for (int i = 0; i <; i++) {j = k++;} System.out.println (j);}

The run result is 99. It is then analyzed:

At the end of each cycle, the memory used to hold the original value of I will be destroyed, and then the new value of I will be placed in a new memory, in the loop above, so the end can achieve the increase of J data.

(2) for i = i++ case

Summarize:

 Each time the Java compiler encounters a self-increment (referring to a i++), a self-decrement (referring to the i--) operator, it creates a new memory space to hold the value of J before the assignment , which is the cached variable , and then assigns the value of the variable to the left variable.

Extended:

  The results of VisualStudio compilation under Microsoft Windows are different from Java, but under other C language compilers such as GCC, the results are the same as in Java, and it is important to note that because some people use the C compiler but not the compiler under Windows, The results are still consistent with Java, but the results of the compilation run under Windows are not the same, hoping to draw the reader's attention.

The difference between i = i++ and j = i++ in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.