In Stack Overflow,  topic: how to compare Java strings? There are 3.7 million + visitors, which is incredible! This shows that many, many programmers have been plagued by this problem.

Let’s review the questioner’s question:

I have been using “”Operator to compare strings, until the program there is a bug, need to use the .equals()method to solve. Why is this?””Operators and .equals()What is the difference between the method?

And the questioner contrary, when I first started learning Java, the string comparisons have been using the .equals()method, because no matter what books or teachers, have warned me not to directly use the “==” operator to compare, would be a bug. As for why, neither the book nor the teacher helped me figure it out.

Then I take this opportunity to sort out the praised answers on Stack Overflow. Let’s learn and improve together, and upgrade.

  • The “==” operator is used to compare whether two references (storage addresses in memory) are equal and whether they are the same object.
  • .equals() Compares the contents of two objects for equality.

How to understand these two sentences? Let me give an inappropriate and appropriate example.

There are a pair of twins, her sister is Alita, and her sister is Lolita. The eyes of ordinary people are completely incapable of distinguishing between sister and sister, but their mothers can easily recognize them.

.equals() It’s as if we ordinary people see Alita as Lolita, and see Lolita as Alita, they look the same as if they were the same person; the “==” operator is like their mother, asking for more Strict, more detailed observation, you can tell who is the sister and who is the sister at a glance.

String alita = new String("小萝莉");
String luolita = new String("小萝莉");

System.out.println(alita.equals(luolita)); // true
System.out.println(alita == luolita); // false

In the case of the above code, the .equals()output is true, and the “==” operator is false-the former is less strict than the latter.

As we all know, Java default for all classes inherit the Object superclass, the class has a named .equals()method, as shown in the source code as follows.

public boolean equals(Object obj) {
    return (this == obj);
}

 

Can see, Object class .equals()method is used by default “”Operator for comparison. If the subclass does not override the method, then””Operator and the .equals()performance of the method is completely the same as – or an object memory address comparing two object references are equal.

But the reality is, there are a lot of rewriting class .equals()method, it is more memory address too heavy, not too realistic scene needs. String class can override the .equals()method, the following source code shown in FIG.

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

 

We can see, if two string objects “==”, then .equals()the result is true; otherwise, compare the contents of two strings are equal.

As you all know, there are two ways to create a string object, as shown below.

String luolita = "小萝莉";
String alita = new String("小萝莉");

 

The first is to create an object in a string constant pool (stored in the method area) and assign a reference to the object to luolita. The second is to create an object in the heap with the new keyword and assign an object reference to alita.

PS: String is the most basic data type and is used very frequently. If it is created every time by the new keyword, it will cost a high time and space. To improve performance and reduce memory overhead, the Java Virtual Machine designed a string constant pool: there is only one object of the same literal.

PPS: The Java virtual machine divides the memory area into several different data areas during program execution, as shown in the following figure.

Below we look at the comparison of strings through the actual code.

The first:

new String("小萝莉").equals("小萝莉") // --> true

 

 

.equals() The comparison is whether the contents of the two string objects are equal, so the result is true.

The second:

new String("小萝莉") == "小萝莉" // --> false

 

 

The object on the left side of the “==” operator is stored in the heap and the object on the right side is stored in the method area, so it returns false.

Third:

new String("小萝莉") == new String("小萝莉") // --> false

 

 

The two new objects must be unequal, so return false.

Fourth:

"小萝莉" == "小萝莉" // --> true

 

 

There will only be one object in the string constant pool, so it returns true.

"小萝莉" == "小" + "萝莉" // --> true

 

 

Since “little” and “loli” are both in the character creation constant pool, the compiler will automatically optimize it to “little loli”, so it returns true.

After analysis of a large number of examples, we can draw the following conclusions (also the answer to the questioner):

  • When comparing the contents of two strings are equal objects, use the .equals()method.
  • When comparing two string objects for equality, use the “==” operator.

Of course, if you want to compare the contents of two string objects, in addition to .equals()the method, there are other alternative methods.

1)Objects.equals()

Objects.equals() The advantage of this static method is that it does not need to be nullified before it is called.

public static boolean equals(Object a, Object b) {
    return (a == b) || (a != null && a.equals(b));
}

If you use it directly a.equals(b), you need to nullify a before calling, otherwise a null pointer may be thrown java.lang.NullPointerException.

Objects.equals("小萝莉", new String("小" + "萝莉")) // --> true
Objects.equals(null, new String("小" + "萝莉")); // --> false
Objects.equals(null, null) // --> true

String a = null;
a.equals(new String("小" + "萝莉")); // throw exception

 

2) of the String class .contentEquals()

.contentEquals() The advantage is that you can compare strings with any sequence of characters (StringBuffer, StringBuilder, String, CharSequence).

public boolean contentEquals(CharSequence cs) {
    // Argument is a StringBuffer, StringBuilder
    if (cs instanceof AbstractStringBuilder) {
        if (cs instanceof StringBuffer) {
            synchronized(cs) {
               return nonSyncContentEquals((AbstractStringBuilder)cs);
            }
        } else {
            return nonSyncContentEquals((AbstractStringBuilder)cs);
        }
    }
    // Argument is a String
    if (cs instanceof String) {
        return equals(cs);
    }
    // Argument is a generic CharSequence
    char v1[] = value;
    int n = v1.length;
    if (n != cs.length()) {
        return false;
    }
    for (int i = 0; i < n; i++) {
        if (v1[i] != cs.charAt(i)) {
            return false;
        }
    }
    return true;
}

 

It can be seen from the source code that if cs is a StringBuffer, the method will also be synchronized, very intelligent. However, it should be noted that before using this method, you need to ensure that the two strings being compared are not null, otherwise a null pointer will be thrown.

Again, .equals()methods need to evaluate to null when comparing, and the “==” operator does not.

System.out.println( null == null); // --> true

 

Well readers, that’s all for this article. You can see all the talents here. The second brother must give you a compliment . If you do n’t find it fun and want to see more, check out my
personal blog

. In addition, to give you a promise, I will update a “program life” and an article about the Java technology stack every week, so stay tuned. If you have any questions that need my help, or want to spray me, please leave a message.

form good habit! If this article is a bit useful, please like, like, follow, share, and leave a message , this will be the strongest motivation for me to write down!

 

Orignal link:https://blog.csdn.net/qing_gee/article/details/103361020