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