Home > Java > Javagetting Started > Java compares strings for equality

Java compares strings for equality

(*-*)浩
Release: 2019-11-14 10:46:20
Original
3917 people have browsed it

Java compares strings for equality

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"
Copy after login

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");
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template