Difference between == and equals in Java?

Difference between == and equals in Java?

== :

When judging the basic type: compare whether the values ​​of two basic data types are the same; for example: int 10 and int 20, return false;

When judging the reference type: the comparison is whether the memory addresses of the two objects are the same, for example: if the two different Integers are 1000, the return value is false; when you need to pay attention: if the values ​​​​of the two different Integers are 10, it returns value is true;

equals:

The equals method is a method provided in the Object class, which is used to define whether the content of the object is equal; (note: the equals method cannot be applied to variables of basic data types)

If the equals method is not rewritten, the address of the object pointed to by the variable of the reference type is compared;

If classes such as String and Date rewrite the equals method, the contents of the pointed objects are compared. For example; to determine whether the String is equal;

First: look at the memory, then look at the data type, then look at whether the length of the string is consistent, and finally compare the contents of the string

Replenish:

In order to save memory inside java, there is an array in the IntegerCache class that caches Integer objects with values ​​from -128 to 127. When we call Integer.valueOf(int i), if the value of i is between -128 and 127, an object will be returned directly from this cache, otherwise a new Integer object will be new. That is: when we define the range of two Integers between [-128—+127] and have the same value, use == to compare the value to true;

When it is greater than 127 or less than -128, even if the two values ​​are the same, a new integer will be created, then the two objects are compared, and false is returned when using == to compare;

Guess you like

Origin blog.csdn.net/weixin_56602545/article/details/130100655