JavaDevNotes.com

Java String Compare

String is one of the most fundamental data structure. It is versatile and useful for many cases. This is why Strings are used in many cases instead of using more restrictive data structure. But sometimes we need to compare two or more Strings for specific programming needs. Below are som examples on how we can compare Strings in Java.

Compare Same String Object

Sometimes we don't want to compare the contents of two strings, but we just want to compare if it is the same object instance. Consider the example below:
public class Test {
    public static void main(String[] args) {
        String firstString = "abc";
        String secondString = "a";
        secondString=secondString+"bc";
        String thirdString = firstString;
        System.out.println("First String is: "+firstString);
        System.out.println("Second String is: "+secondString);
        System.out.println("Third String is: "+thirdString);
        System.out.println(firstString == secondString);
        System.out.println(firstString == thirdString);
    }
}
Although the three strings all have the same values, the first and the second string are not the same object instance. But the first and third strings are the same instance.
First String is: abc
Second String is: abc
Third String is: abc
false
true
One caveat that we need to think about is we can't guarantee that two strings with the same value are different instances. Consider a slightly altered code below:
public class Test {
    public static void main(String[] args) {
        String firstString = "abc";
        String secondString = "abc";
        String thirdString = firstString;
        System.out.println("First String is: "+firstString);
        System.out.println("Second String is: "+secondString);
        System.out.println("Third String is: "+thirdString);
        System.out.println(firstString == secondString);
        System.out.println(firstString == thirdString);
    }
}
We may think that the first and second strings are different instances. But in reality, the Java Virtual machine has a concept of String pool. Java can reuse the same instance if it is already in the pool. We can't control if a new instance will be given to us or not, if the values are the same. Object pool works for String because Strings are immutable objects. The state of the String can't be change. Every time we think we mutated it, it will be a different object. Hence, the result of the above can be:
First String is: abc
Second String is: abc
Third String is: abc
true
true
Also, don't confuse string variable to string variable assignment as assigning pointers similar to C or C++. Consider the code below:
public class Test {
    public static void main(String[] args) {
        String firstString = "abc";
        String secondString = firstString;
        firstString = firstString + "xyz";
        System.out.println("First String is: "+firstString);
        System.out.println("Second String is: "+secondString);
        System.out.println(firstString == secondString);
    }
}
The second string is not a pointer to the first string. Hence, the result of the above code will be:
First String is: abcxyz
Second String is: abc
false

Compare Same String Contents

The most common thing we want to do is to compare if the contents of two strings are the same. For this, we can use the method equals from the String class. Consider the code below:
public class Test {
    public static void main(String[] args) {
        String firstString = "abc";
        String secondString = "xyz";
        String thirdString = "abc";
        System.out.println(firstString.equals(secondString));
        System.out.println(firstString.equals(thirdString));
    }
}
First and second string does not have the same contents, but first and third does. Hence the expected output is:
false
true
Take note that equals is case sensitive. Consider the example below with the same contents but different case.
public class Test {
    public static void main(String[] args) {
        String firstString = "abc";
        String secondString = "Abc";
        System.out.println(firstString.equals(secondString));
    }
}
Both have the contents abc, but the second string has a capital A. The equals in this case will return false because of the difference in case.
false

Compare Same String Contents Case Insensitive

If we want to compare if two Strings are equal but ignoring the case, then we should use equalsIgnoreCase method from the String class. Below is the modified version of the previous example.
public class Test {
    public static void main(String[] args) {
        String firstString = "abc";
        String secondString = "ABC";
        System.out.println(firstString.equalsIgnoreCase(secondString));
    }
}

The method returns true

true

Compare String if Less Than, Equal, or Greater Than

Sometimes we need to know more than if two strings are equal. We may want to know if a String is less than another, greater than one than the other, or just equals. In that case, we can use the method compareTo. Consider the example below:
public class Test {
    public static void main(String[] args) {
        System.out.println("abc".compareTo("abc"));
        System.out.println("aaa".compareTo("abc"));
        System.out.println("ccc".compareTo("abc"));
    }
}
If two Strings are equal, compareTo returns 0. If the first string is less than the second string, it returns a negative number. If the first string is greater than the second then it returns a positive value. The output of the code above will be:
0
-1
2
We can clean up the code above to have a more meaningful output:
public class Test {
    public static void main(String[] args) {
        compare("abc", "abc");
        compare("aaa", "abc");
        compare("ccc", "abc");
    }
    private static void compare(String first, String second) {
        int result = first.compareTo(second);
        if (result == 0) {
            System.out.println(first + " is equal to " + second);
        } else if (result < 0) {
            System.out.println(first + " is less than " + second);
        } else if (result > 0) {
            System.out.println(first + " is greater than " + second);
        }
    }
}
The result now should be:
abc is equal to abc
aaa is less than abc
ccc is greater than abc

But note that compareTo is case sensitive. Hence if we change the string we use, we get a different result:

public class Test {
    public static void main(String[] args) {
        compare("abc", "abc");
        compare("aaa", "ABC");
        compare("CCC", "abc");
    }
    private static void compare(String first, String second) {
        int result = first.compareTo(second);
        if (result == 0) {
            System.out.println(first + " is equal to " + second);
        } else if (result < 0) {
            System.out.println(first + " is less than " + second);
        } else if (result > 0) {
            System.out.println(first + " is greater than " + second);
        }
    }
}
We will now get a different output
abc is equal to abc
aaa is greater than ABC
CCC is less than abc

If we want case insensitive compareTo, there is an alternative method compareToIgnoreCase. Here is the altered example:

public class Test {
    public static void main(String[] args) {
        compare("abc", "abc");
        compare("aaa", "ABC");
        compare("CCC", "abc");
    }
    private static void compare(String first, String second) {
        int result = first.compareToIgnoreCase(second);
        if (result == 0) {
            System.out.println(first + " is equal to " + second);
        } else if (result < 0) {
            System.out.println(first + " is less than " + second);
        } else if (result > 0) {
            System.out.println(first + " is greater than " + second);
        }
    }
}
And we get the output below:
abc is equal to abc
aaa is less than ABC
CCC is greater than abc

Compare String using Apache Commons StringUtils

Apache Commons is a favorite library for all around needs of many Java developers. We can also use the utility class StringUtils of Apache Commons to compare two Strings. Now one may ask, why would we want a utility when it's very simple to do without? The answer is in handling nulls. For example, the code below:
public class Test {
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "a";
        System.out.println(str1.equals(str2));
    }
}
Will throw an exception:
Exception in thread "main" java.lang.NullPointerException
Which is unpleasant. StringUtils' compare method handles nulls better. Consider the code:
public class Test {
    public static void main(String[] args) {
        String str1 = null;
        String str2 = "a";
        System.out.println(StringUtils.compare(str1, str2));
    }
}
Will now output:
-1
Under the hood, this compare method is implemented similar to this:
public static int compare(final String str1, final String str2) {
    if (str1 == str2) {
        return 0;
    }
    if (str1 == null) {
        return -1;
    }
    if (str2 == null) {
        return 1;
    }
    return str1.compareTo(str2);
}
Of course we can create our own utility class for this as this is very simple. But Apache Commons contains numerous utility that we may need anyway. So why not reuse them in our projects? Some methods of interest for comparing Strings are:
  • equals
    public class Test {
        public static void main(String[] args) {
            System.out.println(StringUtils.equals("abc", "abc"));
            System.out.println(StringUtils.equals("abc", "ABC"));
        }
    }
    
    Outputs
    true
    false
    
  • equalsIgnoreCase
    public class Test {
        public static void main(String[] args) {
            System.out.println(StringUtils.equalsIgnoreCase("abc", "abc"));
            System.out.println(StringUtils.equalsIgnoreCase("abc", "ABC"));
        }
    }
    
    Outputs
    true
    true
    
  • compare
    public class Test {
        public static void main(String[] args) {
            System.out.println(StringUtils.compare("abc", "abc"));
            System.out.println(StringUtils.compare("abc", "ABC"));
        }
    }
    
    Will render:
    0
    32
    
  • compareIgnoreCase
    public class Test {
        public static void main(String[] args) {
            System.out.println(StringUtils.compareIgnoreCase("abc", "abc"));
            System.out.println(StringUtils.compareIgnoreCase("abc", "ABC"));
        }
    }
    
    Will result to
    0
    0
    

Support my blog by buying some of my t-shirt, mug, and phone case designs!
                   

String Tutorials And Examples