Java - How to compare String (==, equals, compare)

Let`s see the different ways to compare strings in Java.

I usually use equals in Java to check if a string is equal. Unlike other languages, == does not check for equality of strings. This is because == does not guarantee that the strings an object holds are identical because it checks if the objects are equal. You can also compare strings using the compare method.

Compare strings with equals()

You can use equals() to compare two strings for equality, like this: If you change the order of the objects, the result is the same.

String str1 = "Hello";
String str2 = "World";
String str3 = "Hello";

System.out.println("str1.equals(str2) : " + str1.equals(str2));
System.out.println("str2.equals(str1) : " + str2.equals(str1));
System.out.println("str1.equals(str3) : " + str1.equals(str3));

Output:

str1.equals(str2) : false
str2.equals(str1) : false
str1.equals(str3) : true

equals() is a method defined in Object, the parent class of all objects. String class compares the string passed as an argument by overriding equals() as follows. If you look at the code simply, if the object has the == keyword, it returns true without further checking. If the object is different, if the argument is a String, the string is compared and the result is returned.

// String.java
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;
}

One thing to note while using equals() is that if str1 is null, NullPointerException occurs as follows.

String str1 = null;
String str2 = "World";
System.out.println("a.equals(b) : " + str1.equals(str2));

Conversely, even if the object passed as an argument is null, NullPointerException does not occur.

String str1 = "Hello";
String str2 = null;
System.out.println("a.equals(b) : " + str1.equals(str2));

In fact, if you dont want to worry about throwing NullPointerException like this, you can use Objects.equals()` to compare two objects.

System.out.println("str1 == str2 ? " + Objects.equals(str1, str2));
System.out.println("str1 == str3 ? " + Objects.equals(str1, str3));

If you look at the code implemented in the Objects class, NullPointerException does not occur because null is checked.

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

And when comparing strings, case is also compared. You should use equalsIgnoreCase() to see only the same alphabet, case insensitively.

String str = "Hello";

System.out.println("equals ? " + "Hello".equals(str));
System.out.println("equalsIgnoreCase ? " + "hello".equalsIgnoreCase(str));

Output:

equals ? true
equalsIgnoreCase ? true

Compare strings using ## == Do not use == to compare strings.

If you look at the following example, you can see that there are cases where the string is the same but returns false.

String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");

System.out.println("str1 == str2 ? " + (str1 == str2));
System.out.println("str1 == str3 ? " + (str1 == str3));

System.out.println("str1 hashCode ? " + System.identityHashCode(str1));
System.out.println("str2 hashCode ? " + System.identityHashCode(str2));
System.out.println("str3 hashCode ? " + System.identityHashCode(str3));

Output:

str1 == str2 ? true
str1 == str3 ? false
str1 hashCode ? 1789447862
str2 hashCode ? 1789447862
str3 hashCode ? 38997010

== compares objects for equality, but not the strings they hold.

str1 and str2 are the same object because they both point to the same string "Hello". However, str3 is different from these two in that it is an object created with new String(). System.identityHashCode() is a method that returns the hashCode of an object. This lets you know that str1 and str3 are the same string but different objects.

Compare strings using compareTo()

compareTo() compares two strings. Unlike equals(), which can only check the same, it also returns which character precedes it in lexicographical order. So you can use compareTo() to sort the list in ascending or descending order.

The return value is 0, negative and positive ints are returned, and the meanings are as follows.

  • 0 : Two strings are identical
  • Positive number: the object calling compareTo() has a lexicographical order before the argument.
  • Negative number: Arguments precede the object lexicographically.

You can use it like this:

String str1 = "Hello";
String str2 = "Hello";
String str3 = "World";

System.out.println("str1.compareTo(str2) ? " + str1.compareTo(str2));
System.out.println("str1.compareTo(str3) ? " + str1.compareTo(str3));

System.out.println("str1.compareToIgnoreCase(str2) ? " + str1.compareToIgnoreCase(str2));
System.out.println("str1.compareToIgnoreCase(str3) ? " + str1.compareToIgnoreCase(str3));

Output:

str1.compareTo(str2) ? 0
str1.compareTo(str3) ? -15
str1.compareToIgnoreCase(str2) ? 0
str1.compareToIgnoreCase(str3) ? -15

If str1.compareTo(str3) returns -15, it means that str1 is lexicographically before str3. You can also use compareToIgnoreCase() to compare case insensitively.

Reference

codechachaCopyright ©2019 codechacha