Java self-increasing traps

Source: Internet
Author: User

Title:

public class test{

public static void Main (string[] args) {

int count = 0;

for (int i=0;i<10;i++) {

Count = count++;

}

System.out.println ("count=" +count);

}

}

This code outputs a result of 0, not 10.

count++ is an expression that has a return value, and its return value is the value of the pre-addition, which is handled by Java: first copy the value of Count to a temporary variable area, then add 1 to the count variable, and finally return the value of the temporary variable area.

Therefore, the execution of the above code is: ①JVM Copy the Count value to the temporary variable area, ②count value plus 1, this time the count value is 1;③ return the value of the temporary variable area, note that this value is 0, not modified, ④ the return value is assigned to count, at this point, the count value is reset to 0.

After a loop, the count value is still 0, which is the case for each subsequent loop, and ultimately, the count value is always 0, regardless of the number of cycles.

This article from "brightaries" blog, declined reprint!

Java self-increasing traps

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.