Problems with automatic boxing

Source: Internet
Author: User

In some wrapper objects, such as Integer, if the return value obtained by comparing "= =" between range 128 to 127 is true, then they return the same object, but not in this range. This behavior is usually more dependent on the JVM, so it is best to use the Equals () method to avoid using "= =" when checking.

Example:

Integer i1 = (i1 = = i2) System.out.println ("equal"); Else System.out.println ("unequal");

The result is "not equal". Because in this case, the automatic unpacking is not executed. The literal value of "200" is boxed in two different integer objects (different JVM results may vary), then the objects are compared by "= =" and the result is false because the two objects are different instances and have different memory addresses.

Integer i1=[+]if (i1 = = i2) System.out.println ("equal"); Else System.out.println ("unequal");

The result is "equal" at this time. Because the value of int is within the range of 127 to 127, the JVM caches the value, so "= =" returns the result of true.

Problems with automatic boxing

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.