Be careful with the Value Comparison of encapsulated classes in Java

Source: Internet
Author: User

Generally, we use basic types such as int and long when using numeric values. However, if you like to use Integer and Long packaging classes, pay attention to this. Let's take a look at this Code:

Integer CONST_A = 1 Integer CONST_ B = Integer. valueOf ("2" Integer CONST_C = Integer (3. status = (status = "It's CONST_A" (status = "It's CONST_ B" (status = "It's CONST_C" "Invalid status! "= 123

It's CONST_A
It's CONST_ B
Invalid status!

Some may wonder why the third one does not output It's CONST_C? In fact, jre is quite lazy. If we find that = is an object on both sides, it will directly compare the reference, rather than the value. It is the same as a common object, because the comparison of status 3 is in, the two sides are two different objects, so they are different. But why can the first two? Because IntegerCache exists, the returned Integer is sometimes (why is it sometimes? Because IntegerCache only caches some numeric values, please read the source code) is obtained from the Cache, so they are all the same object, while CONST_C is new when assigning values, so it is not the same as the object in the Cache.

For example, if one side is a packaging class and the other side is a basic type, or if a comparison operator such as <,>, and <= is used, the value is compared. Jre will be lazy and directly compare references only when the conditions for referencing and comparing are met. Therefore, when defining constant variables, it is best to use the basic type, use = and! = Pay more attention.

Ps: The article is short. I don't like to repeat what I can find on the Internet at will, such as packing and unpacking and closed classes. If this article is helpful to you, please support it

Related Article

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.