Integer is an immutable class. after entering a method, changing the value in it will not affect references outside the method.

Source: Internet
Author: User

First look at a small program


The output of the main function does not output 3 as expected. Instead, it outputs the initialized value 0.

This is becauseSimilar to string, all packaging classes are final classes, that is, immutable classes.. Although code A seems to have changed the counter value, it actually creates another object and points the reference of the counter parameter in the method to the newly created object, because it is a different reference, it does not have any impact on references outside the method. The memory diagram is as follows:

When you first enter the method:


After counter = counter + 1 is executed, because integer is an immutable class, to change its value, it actually creates a new object, so the memory figure is as follows:

Integer is an immutable class. after entering a method, changing the value in it will not affect references outside the method.

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.