How to determine whether strings are equal in java:
1. Comparison of strings in java: ==
We often habitually write Above if(str1==str2), this writing method may cause problems in java
example1:
String a="abc"; String b="abc"
Then a==b will return true. Because the value of a string in Java is immutable, only one copy of the same string will be stored in the memory, so a and b point to the same object;
example2 :
String a=new String("abc"); String b=new String("abc");
Then a==b will return false. At this time, a and b point to different objects.
2. Use the equals method to compare whether the contents of the strings are the sameexample:
String a=new String("abc"); String b=new String("abc"); a.equals(b);
(1) For ==, if the function For variables of basic data types (byte, short, char, int, long, float, double, boolean), the stored "values" are directly compared to see if they are equal; if it acts on variables of reference type (String), the comparison is Is the address of the pointed object (that is, whether it points to the same object).
(2) The equals method is a method in the base class Object, so all classes that inherit from Object will have this method. In the Object class, the equals method is used to compare whether the references of two objects are equal, that is, whether they point to the same object.
(3) Note about the equals method: the equals method cannot act on variables of basic data types. If the equals method is not overridden, the address of the object pointed to by the reference type variable is compared; the String class overrides the equals method to compare whether the strings stored in the pointed string objects are equal. . Some other classes, such as Double, Date, Integer, etc., have overridden the equals method to compare whether the contents stored in the pointed objects are equal.
For more java knowledge, please pay attention to the
java basic tutorialThe above is the detailed content of How to determine whether strings are equal in java. For more information, please follow other related articles on the PHP Chinese website!