java string comparison

Regarding == and equals, we need to know the data types in java, which can be divided into two categories:

1. Basic data types, also known as primitive data types. The comparison between byte, short, char, int, long, float, double, boolean
uses the double equal sign (==), and the comparison is their value.
2. When comparing composite data types (classes)
with (==), they compare their storage addresses in memory, so unless it is the same new object, the result of their comparison is true , otherwise the result of the comparison is false. All classes in JAVA inherit from the base class Object, and an equals method is defined in the base class of Object. The initial behavior of this method is to compare the memory address of the object, but in some class libraries, this method is used as an equals method. Overwritten, such as String, Integer, Date in these classes, equals has its own implementation, instead of comparing the storage address of the class in the heap memory.
For the equals comparison between composite data types, without overriding the equals method, the comparison between them is still based on the address value of their storage location in memory, because the equals method of Object also uses a double equals sign ( ==), so the result of the comparison is the same as the result of the double equals sign (==).

  Because string is a composite data type, equals should be used. If we use == comparison, we must compare their memory addresses, so the result of \1 \2 is obvious

  To judge whether two objects are equal, you cannot compare the references of the two objects to be equal, which will never get the same result, because the references of the two objects will never be equal, so the correct comparison method is to directly Compare these two objects, and compare whether the essence of the two objects is the same, that is, whether the contents of the two objects are the same, and determine whether the two objects are equal by comparing whether the attribute values ​​of the two objects are the same. .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325989403&siteId=291194637