How to Compare Strings in Java

  1. String Comparison with String Class
    1. Example
    2. Syntax:
    3. Example
    4. Example
    5. Syntax:
    6. Example
    7. Syntax:
    8. Example
    9. Example
  2. String Comparison with Objects Class
    1. Example
  3. String Comparison with Apache Commons
    1. Example
    2. Example
    3. Example
    4. Example
    5. Example
    6. Example

String is a sequence of characters. It is a data type which is commonly used in Java, thus the comparison of strings is one of the mostly used Java operations. However, very often the developers cannot cope with this operation. If you’re trying to deal with that problem, you’re at the right place! In this article we are going to present different ways to compare strings in Java.

String Comparison with String Class

This method suggests five different ways to compare strings in Java. We are going to take into consideration each of them.

1.1. Using “==” Comparison Operator

Attention: The “==” operator only compares references, not values. So this is an incorrect way to compare text values. Let’s see an example:

Example

String string1 = "using comparison operator";
String string2 = "using comparison operator";
String string3 = new String("using comparison operator");
  
assertThat(string1 == string2).isTrue();
assertThat(string1 == string3).isFalse();

As you can see, the two variables point to the same String literal, that’s why the first assertion is true, but the second assertion is false because string1 is created with a literal and string3 is created with the new operator, which means that they reference different objects.

1.2. Using equals()

This method compares two strings based on their content. It's a comparison by character, which ignores their address. If the two strings are of the same length and the characters are in the same order, it considers them equal and returns true. It returns false if the characters don’t match.

String class suggests two methods

  • public boolean equals(Object another) compares this string to the specified object.
  • public boolean equalsIgnoreCase(String another) compares this string to another string, ignoring case.

Syntax:

str1.equals(str2);

Let’s now see some examples:

Example

String string1 = "comparing strings";
String string2 = "comparing strings";
         
String string3 = "comparing STRINGS";
String string4 = new String("comparing strings");
 
assertThat(string1.equals(string2)).isTrue();
assertThat(string1.equals(string4)).isTrue();
 
assertThat(string1.equals(null)).isFalse();
assertThat(string1.equals(string3)).isFalse();

In this example, string1, string2, and string4 variables are equal because they have the same case and value irrespective of their address.

For string3 the method returns false, as it’s case sensitive.

Also, if any of the two strings is null, then the method returns false.

Now let’s have a look at another example to make sure you got it.

Example

public class CompareStrings {

    public static void main(String[] args) {

        String style = new String("Bold");
        String style2 = new String("Bold");

        if(style.equals(style2))
            System.out.println("Equal");
        else
            System.out.println("Not Equal");
    }
}

Here the output will be “Equal”.

1.3. Using equalsIgnoreCase()

As mentioned above, there also exists another method, which returns a boolean value. This method ignores the case of the characters while comparing Strings.

Syntax:

str2.equalsIgnoreCase(str1);

Example

String string1 = "using equals ignore case";
String string2 = "USING EQUALS IGNORE CASE";
 
assertThat(string1.equalsIgnoreCase(string2)).isTrue();

1.4. Using compareTo()

This method compares the characters of two strings lexicographically according to a dictionary or the natural ordering. It returns an integer value that describes if the first string is less than, equal to or greater than the second string.

Let’s imagine string1 and string2 are two different variables. There are three possible scenarios:

  • string1 == string2 :0
  • string1 > string2 :positive value
  • string1 < string2 :negative value

Syntax:

int str1.compareTo(String str2)

It’s high time we saw an example:

Example

String author = "author";
String book = "book";
String duplicateBook = "book";
 
assertThat(author.compareTo(book))
  .isEqualTo(-1);
assertThat(book.compareTo(author))
  .isEqualTo(1);
assertThat(duplicateBook.compareTo(book))
  .isEqualTo(0);

1.5. Using compareToIgnoreCase()

This is the same method that the previous one. The only difference is that this method ignores the case.

Example

String author = "Author";
String book = "book";
String duplicateBook = "BOOK";
 
assertThat(author.compareToIgnoreCase(book))
  .isEqualTo(-1);
assertThat(book.compareToIgnoreCase(author))
  .isEqualTo(1);
assertThat(duplicateBook.compareToIgnoreCase(book))
  .isEqualTo(0);

String Comparison with Objects Class

An utility class Objects contains an equals() method. It can equally be useful to compare two strings.

This method firstly compares the two strings according to their address, and if they are the same, it returns true. If both arguments are null, it returns true, but if one argument is null, it returns false. It's a case sensitive method because it internally calls the equals() method of the String class.

Let’s check it out with an example.

Example

String string1 = "using objects equals";
String string2 = "using objects equals";
String string3 = new String("using objects equals");
 
assertThat(Objects.equals(string1, string2)).isTrue();
assertThat(Objects.equals(string1, string3)).isTrue();
 
assertThat(Objects.equals(null, null)).isTrue();
assertThat(Objects.equals(null, string1)).isFalse();

String Comparison with Apache Commons

The Apache Commons library contains a utility class for string-related operations, which is called String utils and provides useful methods for string comparison. Let’s check them out.

3.1. Using equals() and equalsIgnoreCase()

We have already presented the equals() method of the String class and found out that it doesn’t handle null values. On the contrary, the equals() method of the StringUtils class also accepts null values. So, we can say that this is the upgraded version of the one belonging to the String class.

Example

assertThat(StringUtils.equals(null, null))
  .isTrue();
assertThat(StringUtils.equals(null, "equals method"))
  .isFalse();
assertThat(StringUtils.equals("equals method", "equals method"))
  .isTrue();
assertThat(StringUtils.equals("equals method", "EQUALS METHOD"))
  .isFalse();

The equalsIgnoreCase() method of StringUtils returns a boolean value. This works similarly to equals(), except it ignores casing of characters in Strings.

Example

assertThat(StringUtils.equalsIgnoreCase("equals method", "equals method"))
  .isTrue();
assertThat(StringUtils.equalsIgnoreCase("equals method", "EQUALS METHOD"))
  .isTrue();

3.2. Using equalsAny() and equalsAnyIgnoreCase()

The first argument of the equalsAny() method is a String and the second one is a multi-args type CharSequence. This method will return true if any of the other Strings given will match against the first String case-sensitively. If not, it will return false.

Now have a look at the following example.

Example

assertThat(StringUtils.equalsAny(null, null, null))
  .isTrue();
assertThat(StringUtils.equalsAny("equals any", "equals any", "any"))
  .isTrue();
assertThat(StringUtils.equalsAny("equals any", null, "equals any"))
  .isTrue();
assertThat(StringUtils.equalsAny(null, "equals", "any"))
  .isFalse();
assertThat(StringUtils.equalsAny("equals any", "EQUALS ANY", "ANY"))
  .isFalse();

The equalsAnyIgnoreCase() method is the same as the previous one, but in addition to it, this method ignores the casing.

Example

assertThat(StringUtils.equalsAnyIgnoreCase("ignore case", "IGNORE CASE", "any")).isTrue();

3.3. Using compare() and compareIgnoreCase()

You are already familiar with the compareTo() method of the String class. The compare() method of the StringUtils class is the null-safe version of the previous one, as it handles null values by considering them less than a non-null value. Two null values are considered to be equal.

This method is used to sort a list of Strings with null entries.

Example

assertThat(StringUtils.compare(null, null))
  .isEqualTo(0);
assertThat(StringUtils.compare(null, "abc"))
  .isEqualTo(-1);
assertThat(StringUtils.compare("abc", "bbc"))
  .isEqualTo(-1);
assertThat(StringUtils.compare("bbc", "abc"))
  .isEqualTo(1);

The compareIgnoreCase() method is the same, but it also ignores casing.

Example

assertThat(StringUtils.compareIgnoreCase("Abc", "bbc"))
  .isEqualTo(-1);
assertThat(StringUtils.compareIgnoreCase("bbc", "ABC"))
  .isEqualTo(1);
assertThat(StringUtils.compareIgnoreCase("abc", "ABC"))
  .isEqualTo(0);

These are different ways to compare strings in Java. Hope you found it useful.


Do you find this helpful?

Related articles