String Comparison in Java
In this article, we will look at the many ways you can use to compare strings in Java. Without beating around the bush, we shall directly jump into the different ways to compare the given strings.
To grasp the concept faster and master it quickly, I suggest you practice each code in the article, try to make some modifications, and tinker with the code to cover different scenarios. This will help you understand the code better and learn how to apply it in different situations.
Comparing Strings using a user-defined method
One way to compare 2 strings is to create a custom user-defined method that tells if the strings are lexicographically the same or not.
Here is an example:
public class FirstCode { public static int stringCompare(String str1, String str2) { int l1 = str1.length(); int l2 = str2.length(); int lmin = Math.min(l1, l2); for (int i = 0; i < lmin; i++) { int str1_ch = (int)str1.charAt(i); int str2_ch = (int)str2.charAt(i); if (str1_ch != str2_ch) {return str1_ch - str2_ch;} } if (l1 != l2) {return l1 - l2;} else {return 0;} } public static void main(String args[]) { String string1 = new String("FirstCode"); String string2 = new String("First"); String string3 = new String("Code"); String string4 = new String("Code"); System.out.println("The difference in length between " +string2 + " and "+string1+ " : " +stringCompare(string2, string1)); System.out.println("The difference in length between " +string3 + " and " + string4+ " : " +stringCompare(string3, string4)); System.out.println("The difference in length between " +string1 + " and " + string4 + " : " +stringCompare(string1, string4)); } }
Output:
The difference in length between First and FirstCode: -4
The difference in length between Code and Code: 0
The difference in length between FirstCode and Code: 3
In the above example, we used a user-defined function called “stringCompare” that compares the lengths of the input string and then prints the difference between both the string lengths if they are not of the same length.
Comparing strings using the method String.equals() in Java
In Java, the inbuilt method string equals() compares the two given strings based on the content of the string; for example, the function will return true if the two strings are identical and false if any characters are different.
This means that the function will compare the two strings character by character, and if any characters are different, the function will return false. If all of the characters are the same, the function will return true.
Before we examine an example of this method, let’s examine its syntax to better understand its usage.
To compare ‘string1’ to ‘string2’, we use the following syntax:
string1.equals(string2); Here is an example of a program using the string equals() function: public class FirstCode { public static void main(String args[]) { String string1 = new String("First"); String string2 = new String("Code"); String string3 = new String("FirstCode"); String string4 = new String("FirstCode"); String string5 = new String("firstcode"); System.out.println(string1+" and " +string2+ " : " +string1.equals(string2)); System.out.println(string3+" and " +string4+ " : " +string3.equals(string4)); System.out.println(string4+" and " +string5+ " : " +string4.equals(string5)); System.out.println(string1+" and " +string4+ " : " +string1.equals(string4)); } }
Output:
First and Code: false
FirstCode and FirstCode: true
FirstCode and firstcode: false
First and FirstCode: false
Comparing strings using the method String.equalsIgnoreCase() in Java
The built Java method String.equalsIgnoreCase() compares two strings irrespective of the case of the string, which means that they can be either lower or upper case.
Similar to the String.equals() method, this method also returns true if the argument is not null and the contents of both the Strings are the same, else false, but this method ignores the case of the strings.
The syntax is also very similar to the string.equals() method. For example, to compare string1 to string2 by ignoring their case, use the following syntax:
string1.equalsIgnoreCase(string2);
Here is a program that makes use of the String.equalsIgnoreCase():
public class FirstCode { public static void main(String args[]) { String string1 = new String("First"); String string2 = new String("Code"); String string3 = new String("FirstCode"); String string4 = new String("FirstCode"); String string5 = new String("firstcode"); System.out.println(string1+" and " +string2+ " : " +string1.equalsIgnoreCase(string2)); System.out.println(string3+" and " +string4+ " : " +string3.equalsIgnoreCase(string4)); System.out.println(string4+" and " +string5+ " : " +string4.equalsIgnoreCase(string5)); System.out.println(string1+" and " +string4+ " : " +string1.equalsIgnoreCase(string4)); } } First and Code : false FirstCode and FirstCode : true FirstCode and firstcode : true First and FirstCode : false
Comparing strings using the method Object.equals() in Java
This method returns true if the arguments are equal and false otherwise. If both arguments are null, true is returned. If exactly one argument is null, false is returned. Otherwise, equality is determined by calling the equals() method on the first argument.
For example, if the first argument is a String and the second argument is an Integer, the method will return false. This is because the two types are different.
If, however, both of the arguments are Strings, the method will return true if the two Strings are equal. This is because the equals() method of the String class compares the contents of two Strings to determine if they are equal.
The equals() method is a powerful tool that can be used to compare objects of different types. It is important to understand how the equals() method works in order to use it effectively.
Here is an example:
import java.util.*; public class FirstCode { public static void main(String args[]) { String string1 = new String("First"); String string2 = new String("Code"); String string3 = new String("FirstCode"); String string4 = new String("FirstCode"); String string5 = null; String string6 = null; System.out.println(string1+" and " +string2+ " : " +Objects.equals(string1, string2)); System.out.println(string3+" and " +string4+ " : " +Objects.equals(string3, string4)); System.out.println(string4+" and " +string5+ " : " +Objects.equals(string4, string5)); System.out.println(string1+" and " +string4+ " : " +Objects.equals(string1, string4)); System.out.println(string6+" and " +string5+ " : " +Objects.equals(string6, string5)); } }
Output:
First and Code: false
FirstCode and FirstCode: true
FirstCode and null: false
First and FirstCode: false
null and null: true
Comparing strings using the method String.compare.to()
This method compares both strings lexicographically. Yup, exactly like the first example, except this method is an inbuilt method in Java. It essentially returns the difference between the lengths of the strings if they are not of the same length. If they are of the same length, it returns 0.
Here is an example:
public class FirstCode { public static void main(String args[]) { String string1 = new String("First"); String string2 = new String("Code"); String string3 = new String("FirstCode"); String string4 = new String("FirstCode"); String string5 = new String("firstcode"); System.out.println(string1+" and " +string2+ " : " +string1.compareTo(string2)); System.out.println(string3+" and " +string4+ " : " +string3.compareTo(string4)); System.out.println(string4+" and " +string5+ " : " +string4.compareTo(string5)); System.out.println(string1+" and " +string4+ " : " +string1.compareTo(string4)); } }
Output:
First and Code: 3
FirstCode and FirstCode: 0
FirstCode and firstcode: -32
First and FirstCode: -4
Can we compare strings using the “==” sign?
Sadly, no, actually, yes…well…it’s complicated! we cannot compare strings using “==” as it will compare the reference of the string, meaning if they are the same object or not. The thing is, it works, but it is not recommended as it only compares the reference of the string. Unlike numbers, the “==” does not compare values for strings.
Here is an example:
public class FirstCode { public static void main(String[] args) { if("FirstCode" == "FirstCode") System.out.println("Strings are same"); else System.out.println("Strings are not the same"); } }
Output:
Strings are same
Comparing strings using mathematical comparators
Just like numbers, we can compare strings also using the comparators “!=”, “>”, “<”, and “==”. Below is a code that illustrates the same:
import java.util.Scanner; public class StringComparatorExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Taking two strings as input System.out.println("Enter the first string:"); String str1 = scanner.nextLine(); System.out.println("Enter the second string:"); String str2 = scanner.nextLine(); // Using comparators to compare strings if (str1.equals(str2)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are not equal."); // Using ">" comparator if (str1.compareTo(str2) > 0) { System.out.println("The first string is greater than the second string."); } // Using "<" comparator if (str1.compareTo(str2) < 0) { System.out.println("The first string is less than the second string."); } // Using "!=" comparator if (!str1.equals(str2)) { System.out.println("The strings are not equal."); } } scanner.close(); } }
Output:
Enter the first string:
First
Enter the second string:
Code
The strings are not equal.
The first string is greater than the second string.
The strings are not equal.
Conclusion
You have now learned multiple how to compare strings in Java as we looked at comparing strings using a user-defined method, string.equals(), string.equalsIgnoreCase(), Object.equals(), String.compare.to(), and more.