1. Introduction
Knowing how to compare String in Java is essential to writing software applications – comparing user inputs or ensuring two text files are identical. In this article, we’ll explore the various methods available to compare Strings in Java and make quick and accurate side-by-side comparisons with ease!
2. Various Ways to Compare String Objects in Java
Java String objects are immutable, meaning they remain constant and cannot be altered after coming into existence. A String is simply a collection of characters gathered together.
There are 3 primary ways to compare String in Java, and we will take a look at each one in detail:
- By using the equals() method
- By the compareTo() method
- By utilising == Operator
2.1. Compare via Equals() Method
The equals method belongs to the Object class; however, the String class overrides it. We are comparing using equals for value equality, not the object identity.
The string object equals method assesses the two given string objects by examining their contents. If all characters of both strings are identical, it will return true; however, if any figures diverge even slightly, false is returned.
private static void compareUsingEquals() { String elementOne = "text"; String elementTwo = "text"; String elementThree = "TEXT"; String elementFour = "text2"; System.out.println(elementOne.equals(elementTwo)); // true System.out.println(elementOne.equals(elementThree)); // false System.out.println(elementOne.equals(elementFour)); // false }
In the example above, we compare Strings in Java. String one with two; the equals method will return true because both comparing Strings contain the same character sequence.
When we compare Strings three and four, we will get a false because equals is case-sensitive, and element four has an extra character at the end.
2.2. EqualsIgnoreCase Method
The String object equalsIgnoreCase method is very similar to the equals method in string comparison; however, it is not case-sensitive. If both String objects contain identical characters while disregarding their uppercase/lowercase differences, this method returns true; otherwise, it yields false if one of the arguments is null.
private static void compareUsingEqualsIgnoreCase() { String elementOne = "text"; String elementTwo = "TEXT"; System.out.println(elementOne.equalsIgnoreCase(elementTwo)); // true }
3. Compare via compareTo()
The compareTo compare Strings characters alphabetically according to the dictionary. The output of this operation is an integer that indicates whether the first String object has a lesser, equal or greater value than the second String.
When this method is used, it will return 0 if two String objects are the same, a negative number if the first String appears before the argument; and a positive number if the initial String object occurs afterwards.
private static void compareUsingCompareTo() { String elementOne = "text"; String elementTwo = "text"; String elementFour = "sentence"; System.out.println(elementOne.compareTo(elementFour)); // 1 System.out.println(elementFour.compareTo(elementOne)); // -1 System.out.println(elementOne.compareTo(elementTwo)); // 0 }
We get a positive integer when the element one String object lexicographically precedes the element two argument String. We will get a negative result if we compare the same Strings swapping their place naturally. 0 results can be achieved when both Strings are equal or null.
3.1. CompareToIgnoreCase Method
The compareToIgnoreCase method compares similarly to compareTo but ignores case sensitivity when it comes to String in Java.
private static void compareUsingCompareToIgnoreCase() { String elementOne = "text"; String elementTwo = "TEXT"; System.out.println(elementOne.compareToIgnoreCase(elementTwo)); // 0 }
4. Using “==” Operator
When comparing strings in Java, both the equals() and == operators can be used, yet there are a few discrepancies between them. Let’s take an in-depth look at these differences now.
When comparing two String objects, we use the == operator for reference (memory address comparison) and the equals method for content comparison.
Simply put, == checks if two Strings point to the same memory location while equals evaluate whether or not the values of these two Strings are equal.
Let’s take a look at the example below:
private static void compareUsingEqualsSign() { String elementOne = "text"; String elementTwo = "text"; String elementThree = new String("text"); System.out.println(elementOne == elementTwo); System.out.println(elementOne == elementThree); }
Strings in Java reside in a string pool, so creating two Strings with the same character sequence will point to the same reference. This is why the first comparison will return true.
When you create a String object using a new operator, a new reference will be created in the Java heap space. Hence why the second compare Strings method will return false because element three points to a different reference from the other two Strings.
This is considered bad practice because we occupy more memory in a string pool than necessary.
5. String Comparison With Objects Utility Class
Objects offers a utility class for comparing Strings with a static equals method. This method returns true if two Strings are equal by evaluating their memory addresses in the same manner as the == operator.
As a result, if neither argument is null, it returns true, whereas if exactly one argument is null, the returned value will be false. Otherwise, the program invokes the passed argument’s type class’ equals method – which would be String’s equals method.
This function considers upper and lower cases since it internally calls String class’ equals.
private static void compareUsingObjects() { String elementOne = "text"; String elementTwo = "text"; String elementThree = new String("text"); System.out.println(Objects.equals(elementOne, elementTwo)); System.out.println(Objects.equals(elementOne, elementThree)); }
So, in this case, both calls to the Objects equals method will return true.
6. String Comparison With Apache Commons
If you still wonder how to compare String in Java, the Apache Commons library provides an alternative way to compare String with its invaluable utility class, StringUtils.
The equals method in the StringUtils​ class is a superior form to the conventional ​String​ class method, allowing for null values to be easily handled.
private static void compareUsingApacheCommonsEquals() { String elementOne = "text"; String elementTwo = "TEXT"; String elementThree = null; String elementFour = "sentence"; System.out.println( StringUtils.equals(null, elementThree)); // true System.out.println( StringUtils.equals(elementOne, elementOne)); // true System.out.println( StringUtils.equals(elementOne, elementTwo)); // false System.out.println( StringUtils.equals(elementThree, elementFour)); // false }
6.1. Compare and compareIgnoreCase
StringUtils method does compare strings safely due to the approach to comparing strings when null values are included; in fact, it considers two nulls equal! On top of that, it also considers any non-null value as larger than a null one.
The compareIgnoreCase compares String again but also ignores casing. Take a look at the following example:
private static void compareUsingApacheCommonsEquals() { String elementOne = "text"; String elementTwo = "TEXT"; String elementThree = null; String elementFour = "sentence"; System.out.println( StringUtils.compare(null, elementThree)); // 0 System.out.println( StringUtils.compare(elementOne, elementFour); // 1 System.out.println( StringUtils.compare(elementFour, elementOne); // -1 System.out.println( StringUtils.compare(elementThree, elementFour)); // -1 System.out.println( StringUtils.compareIgnoreCase(elementOne, elementTwo)); // 0 System.out.println( StringUtils.compareIgnoreCase(elementOne, elementFour); // 1 System.out.println( StringUtils.compareIgnoreCase(elementFour, elementOne); // -1 }
6.2. EqualsAny and EqualsAnyIgnoreCase
The equalsAny compare Strings method requires two arguments – a case-sensitive String and a multi-args type of CharSequence. If any other given Strings match the initial String, this method will return true; otherwise, it produces false.
The EqualsAnyIgnoreCase method compares similarly but ignores character casing. The below example presents both methods when comparing Strings in Java:
private static void compareUsingApacheCommonsEqualsAny() { String one = "text"; String two = "TEXT"; String three = null; String four = "sentence"; System.out.println( StringUtils.equalsAny(three, three, three)); // true System.out.println( StringUtils.equalsAny(one, two, four); // false System.out.println( StringUtils.equalsAny(one, three, one); // true System.out.println( StringUtils.equalsAny(one, three, four)); // false System.out.println( StringUtils.equalsAnyIgnoreCase(one, two, four)); // true System.out.println( StringUtils.equalsAnyIgnoreCase(elementOne, elementFour); // 1 System.out.println( StringUtils.equalsAnyIgnoreCase(elementFour, elementOne); // -1 }
7. Summary
We have looked at how to compare String in Java, which can be tricky – don’t assume that using the “==” sign will cut it! As it turns out, creating a String with the new operator is like opening Pandora’s box: you may end up with more references than intended. So think twice before pulling this lever!
Daniel Barczak
Daniel Barczak is a software developer with a solid 9-year track record in the industry. Outside the office, Daniel is passionate about home automation. He dedicates his free time to tinkering with the latest smart home technologies and engaging in DIY projects that enhance and automate the functionality of living spaces, reflecting his enthusiasm and passion for smart home solutions.
Leave a Reply