Comparison of strings in java: ==
We often habitually write if(str1==str2) , this way of writing may cause problems in java
example1: (Recommended learning: java course)
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. The equals method is used to compare whether the contents of the strings are the same.
example:
String a=new String("abc"); String b=new String("abc"); a.equals(b);
will return true.
The equals comparison content of the String class has the same idea as follows:
1, First determine whether the addresses are equal, and return true if they are equal
2. Compare whether the types are the same or not, return false
3. Convert the incoming object to String and compare the lengths. The lengths are not equal. Return false
4. The lengths are equal, and the elements of the character array are compared in a loop. When there is an element with different contents, false is returned immediately
5. Two character arrays are looped. Compare all elements, if there are no elements with different contents, return true
The above is the detailed content of Java compares strings for equality. For more information, please follow other related articles on the PHP Chinese website!