How to compare strings in java

Nimesha Wijepala
5 min readNov 15, 2020

What is a String

Well, String is the data type that we usually use for storing an immutable sequence of characters, simply a non-modifiable character array. A String is not a primitive variable type but a java class. The compiler creates objects of the String class when we use a string literal in our code. String literal means variable value inside double-quotes. Also, we can implement strings simply by creating String objects with the “new” keyword.

As a novel java programmer it is very important to understand how to compare two Strings. The String class has several methods for comparing two Strings. But we need to know what method is the most suitable one for our implemented logic. Let’s see what are those comparison methods which we can use.

“=” Operator

Actually “=” is not a recommended way to compare strings because it only checks whether the strings are sharing the same address space in the memory. But String objects can contain the same values which are pointed to different memory locations. See the following example to understand why we should not use “=” to compare strings in our code.

public class StringComparisonTest {public static void main(String[] args) {
String firstString = "I am String";
String secondString = "I am String";
String thirdString = new String("I am String");
System.out.println(firstString == secondString);
System.out.println(firstString == thirdString);
}
}
Output:
true
false

boolean equals(Object anObject)

As we all know Object class is the parent class of all java classes. The method, boolean equals(Object anObject) is one method of Object class and String class is overriding it for comparing two String objects. Let’s understand how the “equals()” method compares two strings.

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;
}

First, it checks whether given two objects point to the same memory location using the “=” operator. It optimizes the method performance. The second step is checking whether the passed object is a String object, using instanceof operator. Here instanceof operator checks for null and casts the given object to String object. Finally, it checks each character of the given string is similar to the comparing string converting both of them to char arrays. If both character sequences are similar, the method returns true otherwise false.

boolean equalsIgnoreCase(String anotherString)

We can simply use the above method for comparing two strings ignoring case sensitivity. Let’s see the logic inside the method.

public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true :
(anotherString != null) &&
(anotherString.value.length == value.length) &&
regionMatches(true, 0, anotherString, 0, value.length);
}

This method has only one line but checks several conditions. First, it checks whether the given two strings are sharing the same address space using the “=” operator. If it is true the method simply returns true, optimizing the code performance. Otherwise, it checks for three conditions; checking for null, length similarity, and the result of regionMatches method. Through the regionMatches method, character sequences of strings are compared by converting them to upper and lower cases and returns true for similar character sequences. If these three conditions return true, the equalsIgnoreCase method also returns true and otherwise false.

int compareTo(String anotherString)

compareTo method compares two strings using their ASCII values called lexicographic comparison. Let’s see what happens inside the method.

public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}

First, it gets the minimum length of the given two strings and then reads both strings as char arrays. It continues looping increasing an integer value until the minimum length from two strings arrives. Inside the loop, there is a condition that checks the similarity between both character array values one by one. If comparing character values are different, the method simply returns the subtraction of their ASCII values. If all of both char array values are similar to each other, the method simply returns the length difference of the given strings. So it returns zero because the length difference is similar to zero if both strings are equal.

Also, there is no implementation for the null check inside the compareTo method which means it does not accept null values like the previous methods we discussed.

int compareToIgnoreCase(String str)

The only difference between compareTo and compareToIgnoreCase methods is ignoring the case sensitivity in the compareToIgnoreCase method. It behaves and returns int values as same as the previous method we discussed earlier.

What is the best

Well, there is no best method in which we can always choose to compare two strings but all four we discussed are better than the “=” operator. We have to select the comparison method considering both reasons, ideally suitable for the logic we use and optimizing the performance of our code. As an example, the equalsIgnoreCase method is much better than the equals method if we can ignore the case sensitivity because equals work on an object parameter while equalsIgnoreCase works with a string parameter. The following code snippet simply shows how to use discussed methods in action.

public class StringComparisonTest {public static void main(String[] args) {String firstString = new String("I am String");
String secondString = new String("I am String");
String thirdString = new String("I am String but different");
System.out.println(firstString.equals(secondString)); System.out.println(firstString.equalsIgnoreCase(secondString));
System.out.println(firstString.compareTo(secondString));
System.out.println(firstString.compareToIgnoreCase(secondString));
System.out.println(firstString.equals(thirdString));
System.out.println(firstString.equalsIgnoreCase(thirdString));
System.out.println(firstString.compareTo(thirdString));
System.out.println(firstString.compareToIgnoreCase(thirdString));
}
}
Output:
true
true
0
0
false
false
-14
-14

Well, from today onwards you can select the best string comparison method for your own code because you know how they behave internally now. Well, it is your choice. Let’s go ahead with lovely programming.

--

--

Nimesha Wijepala

One who work in software industry as well as loves writing. Trying to combine both for sharing knowledge all over the world.