Java packaging class comparison

Source: Internet
Author: User

When we use '=' to compare the basic type, the value is compared.

However, when the = Operator is used to compare the wrapper object, it is used to check whether the object value is directed to the same storage region. Therefore, the following comparison is generally not true:

Integer A = 1000; integer B = 1000; if (a = B )...

But Java implementation may make it true: (Change 1000 to 100)

Integer A = 100; integer B = 100; if (a = B )...

Why?

It turns out that the automatic packaging operation is involved here, and the int type is automatically packaged into an integer type. WhileThe automatic packaging specification must be boolean, byte, char <= 127, ranging from-128 ~ The short and INT values between 127 are encapsulated into a fixed object, that is, the same memory area..

To avoid this problem, we recommend that you use the equals method to compare whether objects are equal, instead of using the = Operator to compare whether objects are the same.

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.