"Java doubts" prefix self-increment and suffix self-increment auto-decrement problem

Source: Internet
Author: User


The following code:

public class Example025 {public static void main (string[] args) {int ape = 100;int it = 100;int ape_it = 100;for (int i = 0; I < 100; i++) {ape--;it = It--;ape_it =--ape_it;} System.out.println ("ape =" + ape); System.out.println ("it =" + it); ErrorSystem.out.println ("ape_it =" + Ape_it);}}

Output Result:

Ape = 0it = 100ape_it = 0


Cause Analysis:

There should be no objection to the ape's output. But why the value of it is still 100, why is the value of Ape_it 0. First said Ape_it: In the Loop, the ape_it first self-reduction, and then assign value, in fact, the assignment here is meaningless, so the output is 0.

The process of assigning it is more cumbersome. First, take the value of it, then it's self-subtract, then assign a value. The assignment is after self-subtraction, but the assigned value is the value before the decrement. This process, the value of it self-reduction does not play any role. "it=it--;" can be expressed using the following more graphic code:

int tmp = it; Value it = it-1;//minus one it = tmp;//re-assignment

The above code allows you to clearly understand why the value of it has not changed. A deeper understanding can be found in article http://my.oschina.net/0x0001/blog/168968. The lesson from this is that you do not assign values to the same variable more than once in a single expression.


Source code Address: Https://github.com/rocwinger/java-disabuse


This article from "Winger" blog, declined reprint!

"Java doubts" prefix self-increment and suffix self-increment auto-decrement problem

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.