Introduction to the self-increasing problem in Java _java

Source: Internet
Author: User

Run the following code, what's the result?

Package com.test;

Public Class Inc. {public
  
  static void Main (string[] args) {
    inc = New Inc ();
    int i = 0;
    Inc.fermin (i);
    i = i++;
    System.out.println (i);
  }

  void Fermin (int i) {
    i++
  }
}

The result: 0

The above similar code runs in C/s + + to run the result is: 1, this is why?

This is because Java uses the intermediate caching variable mechanism:
i=i++; equal to:
Temp=i (I on the right of the equal sign)
i=i+1; (I on the right of the equal sign)
I=temp; (I on the left of the equal sign)
And I=++i is equivalent to:
i=i+1;
Temp=i;
I=temp;


Detailed

The JVM has two stores, one is registers (is a stack, the following is called a stack), and the other is a variable area.

The JVM will run this statement like this:

Step 1 The JVM copies the value of I (its value is 0) to the temporary variable area (temp=0).

Step 2 is the value of the variable region I plus 1, at which point I is 1.

Step 3 Returns the value of the temporary variable area (temp), note that this value is 0 and has not been modified.

Step 4 Returns the value assigned to the variable area I, at which point the value of I is reset to 0.


There is no additional temporary variable or temporary space to save I in C + +, and all operations are done in one memory space, so it is 1 in C + +.

The above introduction of the Java in the self-increase problem is small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.