Users can compare strings in Java using two ways, i.e., “string reference” comparison and “string content” comparison. When comparing by reference, Java checks if the two strings are stored in the exact same memory location. On the other hand, content comparison checks if the characters in the strings are exactly the same. Most of the time, developers use content comparison to see if the values of two strings are equal or not.
This article will implement 14 different ways to compare strings in Java.
Quick Outlines
- String Comparison Using Equality Operator “==”
- String Comparison Using String Class
- String Comparison Using Objects Class
- String Comparison Using StringUtils Class
- String Comparison Using a User-defined Function
String Comparison Using Equality Operator “==”
The equality operator compares the given strings based on their address (memory location) instead of their values. If two references are pointing/referring to the same object, it retrieves “true”, else it returns “false”.
Example 1: How to Compare Strings in Java Using Equality Operator
Declare three strings and initialize them with some values to compare:
String string1 ="Java";
String string2 ="Java";String string3 ="Beat";
Now perform a comparison on the created strings using the “==” operator:
System.out.println(string1 + " == " + string2 + ": " + (string1==string2));
System.out.println(string1 + " == " + string3 + ": " + (string1==string3));
Complete Code & Output
Important: Do not use the equality operator if you are supposed to compare string values (because the “==” operator compares the references). In Java, several strings can represent the same string object, so using the equality operator for string comparison may lead to inappropriate results.
Example 2: Problem With Equality Operator
In Java, when a user creates a string object using the “new” operator, a new memory location(address) is created for that object. For instance, create a string and assign it a value “Java”:
String string1 = "Java";
Create one more string using the new operator:
String string4 = new String("Java");
Now compare it with the “string1”, which contains the same value as “string4”:
System.out.println(string1 + " == " + string4 + ": " + (string1==string4));
Complete Code & Output:
String Comparison Using String Class
In Java, the String is a built-in class that offers several methods to perform different tasks on the string data. For instance, it offers various methods to perform string comparisons case-sensitively or case-insensitively.
Method 1: String Comparison Using String.equals()
The String.equals() method performs case-sensitive string comparison. This method performs comparison based on string content. If the given strings match, the stated method returns “true”, else retrieves “false”.
Example: How to Use String.equals() in Java?
First, create four variables and assign them some string values:
String product1 = "Motherboard";
String product2 = "RAM";
String product3 =new String("Motherboard");
String product4 =new String("ram");
Now perform comparisons on the given strings using the “.equals()” method:
System.out.println(product1 + " == " + product2 + ": " + (product1.equals(product2)));
System.out.println(product1 + " == " + product3 + ": " + (product1.equals(product3)));
System.out.println(product2 + " == " + product3 + ": " + (product2.equals(product3)));
System.out.println(product2 + " == " + product4 + ": " + (product2.equals(product4)));
Complete Code & Output:
Method 2: String Comparison Using String.equalsIgnoreCase()
The “String.equalsIgnoreCase()” compares the given strings case-insensitively. It performs comparisons based on string content and returns “true” for a perfect match, else it retrieves “false”.
Example: How to Use String.equalsIgnoreCase() in Java
Create three variables and assign them a string value “RAM” in different case conventions, i.e., uppercase, lowercase, mixed case:
String product1 = "rAM";
String product2 = "RAM";
String product3 =new String("ram");
Now implement the “equalsIgnoreCase()” method on the given strings to perform the string comparison irrespective of their case:
System.out.println(product1 + " == " + product2 + ": " + (product1.equalsIgnoreCase(product2)));
System.out.println(product1 + " == " + product3 + ": " + (product1.equalsIgnoreCase(product3)));
System.out.println(product2 + " == " + product3 + ": " + (product2.equalsIgnoreCase(product3)));
Complete Code & Output:
Method 3: String Comparison Using compareTo()
The String class provides another convenient method named compareTo() that compares the given strings based on the Unicode value of each character (lexicographically comparison). It returns a positive value (>0) if the first string is greater than the second one, a negative value if the first string is less than the second one, and 0 if both of them are equal.
Example: How to Use compareTo() in Java?
First, create some strings to compare:
String product1 = "Motherboard";
String product2 = "RAM";
String product3 = new String("ram");
String product4 = new String("Motherboard");
Now apply the compareTo() method on the input strings to compare them lexicographically:
System.out.println(product1 + " == " + product2 + ": " + (product1.compareTo(product2)));
System.out.println(product1 + " == " + product3 + ": " + (product1.compareTo(product3)));
System.out.println(product2 + " == " + product3 + ": " + (product2.compareTo(product3)));
System.out.println(product1 + " == " + product4 + ": " + (product1.compareTo(product4)));
Complete Code & Output:
The first compareTo() retrieves “-5” because “M” is 5 times less than “R” (ASCII values). The second compareTo() retrieves “37” because “M” is 37 times less than “r”. Similarly, the “R” is 32 times less than “r”, so the compareTo() method retrieves “-32”. The fourth and final compareTo() returns 0 because both strings are equal.
Method 4: String Comparison Via compareToIgnoreCase()
The compareToIgnoreCase() works similarly to the compareTo() method. The only difference is the compareToIgnoreCase() performs comparison irrespective of their case.
Example: How to Use compareToIgnoreCase() in Java
Consider the same strings that we used in the above example:
String product1 = "Motherboard";
String product2 = "RAM";
String product3 =new String("ram");
String product4 =new String("Motherboard");
Now perform the string comparison on the given strings using the compareToIgnoreCase() method:
System.out.println(product1 + " == " + product2 + ": " + (product1.compareToIgnoreCase(product2)));
System.out.println(product1 + " == " + product3 + ": " + (product1.compareToIgnoreCase(product3)));
System.out.println(product2 + " == " + product3 + ": " + (product2.compareToIgnoreCase(product3)));
System.out.println(product1 + " == " + product4 + ": " + (product1.compareToIgnoreCase(product4)));
Complete Code & Output:
Method 5: String Comparison Using String.regionMatches()
The “regionMatches()” is one of the String methods that is capable of performing string comparison case-sensitively as well as case-insensitively. Also, it allows users to compare the complete strings or only specific parts of the given strings. To do that, it offers two different variants that are discussed in the following syntaxes.
Syntax for Case-sensitive Comparison:
string.regionMatches(int toffset, String target_string, int offset, int length);
Here,
- The “toffset” represents the starting offset of the subregion in the given string.
- The “target_string” is a string to be compared with the given “string”.
- The “offset” denotes the starting offset of the subregion.
- The “length” indicates the total number of characters to compare.
Syntax for Case-insensitive Comparison:
string.regionMatches(boolean ignoreCase, int toffset, String target_string, int offset, int length);
Where “ignoreCase” is a boolean-type parameter that helps us perform case-insensitive comparisons. If “True”, the regionMatches() will perform the comparison irrespective of the letter case.
Example 1: How to Use reigonMatches() for Case-sensitive Comparison
Create a couple of strings to compare:
String string1 = new String("javabeat");
String string2 = new String("welcome to javabeat.net");
Use the regionMatches() method to check if string1 is equal to string2. In the following code, “0”, “string2”,
“0”, and “8” represent the starting index of string1, the target string, the starting index of string2, and the characters to be compared, respectively:
System.out.println("String1 is equal to string2: ");
System.out.println(string1.regionMatches(0, string2, 0, 8));
Now, use the regionMatches() method one more time to check if string1 (javabeat) is a part of string2 (welcome to javabeat.net). For this, specify the starting index of string2 to which you want to compare string1:
System.out.println("String1 is a Part of String2: ");
System.out.println(string1.regionMatches(0, string2, 11, 8));
Complete Code & Output:
Example 2: How to Use reigonMatches() for Case-insensitive Comparison
Specify the boolean “true” as the first argument of the “regionMatches()” method to perform case-insensitive comparison:
System.out.println("Case Sensitive Comparison: ");
System.out.println(string1.regionMatches(0, string2, 11, 8));
System.out.println("Case Insensitive Comparison: ");
System.out.println(string1.regionMatches(true, 0, string2, 11, 8));
Complete Code & Output
String Comparison Using Objects Class
Java’s object class offers an equals() method that accepts two objects as arguments. It compares the given objects and retrieves a boolean true if given objects are equal and false if they are not equal.
Example: How to Compare Strings in Java Using Objects.equals()
To use Objects.equals() method, first, import the Objects class:
import java.util.objects;
Now, apply the Objects.equals() method to compare the given strings:
System.out.println("JavaBeat == javabeat.net: " + (Objects.equals("JavaBeat", "javabeat.net")));
System.out.println("JavaBeat == javabeat: " + (Objects.equals("JavaBeat", "javabeat")));
System.out.println("JavaBeat == JavaBeat: " + (Objects.equals("JavaBeat", "JavaBeat")));
System.out.println("null == null: " + (Objects.equals(null, null)));
Complete Code & Output
String Comparison Using StringUtils Class
StringUtils is a utility class in Java that belongs to a third-party library named “Apache Commons Lang”. It provides several methods to perform various string operations, including string comparison. However, to use this class, users are required to create a Maven or Gradle project and add the Apache Commons Lang dependency in the “pom.xml” or “build.gradle” file, respectively.
For instance, we create a Maven project and add the following dependencies in its “pom.xml” file”:
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
</dependencies>
Once the dependencies are added, we can import the StringUtils class in our program to compare strings in Java:
import org.apache.commons.lang3.StringUtils;
After importing the StringUtils class in our code, we are all set to use any of its methods.
Method 1: String Comparison Using StringUtils.equals()
In Java, the “StringUtils.equals()” method compares the provided strings and yields a boolean value accordingly. The stated method deals with the null values as well.
Example: How to Use StringUtils.equals() in Java
Specify the strings to compare in the StringUtils.equals() method to perform the string comparison:
System.out.println("JavaBeat == javabeat: " + (StringUtils.equals("JavaBeat", "javabeat")));
System.out.println("JavaBeat == JavaBeat: " + (StringUtils.equals("JavaBeat", "JavaBeat")));
System.out.println("null == null: " + (StringUtils.equals(null, null)));
System.out.println("JavaBeat == null: " + (StringUtils.equals("JavaBeat", null)));
The last couple of “System.out.println()” statements show the working of StringUtils.equals() method on null values.
Complete Code & Output
Method 2: String Comparison Using StringUtils.equalsIgnoreCase()
If you want to perform case-insensitive comparisons use the “StringUtils.equalsIgnoreCase()” instead of “StringUtils.equals()”.
Example: How to Use StringUtils.equalsIgnoreCase() in Java
Use the same code as the above example, and replace the “equals()” method with the equalsIgnoreCase() method, as follows:
System.out.println("JavaBeat == javabeat: " + (StringUtils.equalsIgnoreCase("JavaBeat", "javabeat")));
System.out.println("JavaBeat == JavaBeat: " + (StringUtils.equalsIgnoreCase("JavaBeat", "JavaBeat")));
System.out.println("null == null: " + (StringUtils.equalsIgnoreCase(null, null)));
System.out.println("JavaBeat == null: " + (StringUtils.equalsIgnoreCase("JavaBeat", null)));
Complete Code & Output
Method 3: String Comparison Using StringUtils.equalsAny()
The “StringUtils.equalsAny()” method accepts multiple strings as arguments. It compares the first string to all the given strings and returns true if it matches with any of the specified arguments/strings. It performs case-sensitive comparisons.
Example: How to Use StringUtils.equalsAny() in Java
Specify the strings to compare in the equalsAny() method as follows:
System.out.println("String Found: " +
StringUtils.equalsAny("Java", "javabeat", "java", "Java"));
System.out.println("String Found: " +
StringUtils.equalsAny("JavaBeat", "javabeat", "java", "Java", null));
Complete Code & Output
Method 4: String Comparison Using StringUtils.equalsAnyIgnoreCase()
The “equalsAnyIgnoreCase()” method of the StringUtils class serves the same functionality as the equalsAny() method. The case-insensitive behavior is the only parameter that differentiates it from the equalsAny() method.
Example: How to Use StringUtils.equalsAnyIgnoreCase() in Java
Replace the “equalsAny()” with the “equalsAnyIgnoreCase()” in the above code to see how it works in Java:
System.out.println("String Found: " +
StringUtils.equalsAnyIgnoreCase("Java", "javabeat", "java", "Java"));
System.out.println("String Found: " +
StringUtils.equalsAnyIgnoreCase("JavaBeat", "javabeat", "java", "Java", null));
Complete Code & Output
Method 5: String Comparison Using StringUtils.compare()
The “StringUtils.compare()” method works similarly to the “String compareTo()” method. It compares the given strings lexicographically and returns “0” if the given strings are equal. A positive digit (>0) if string1 is greater than string2 and a negative digit if string1 is less than string2. Also, it deals with the null values, effectively. It considers a non-null value greater than the null value.
Example: How to Use StringUtils.compare() in Java
The following code uses the compare() method to compare different strings:
System.out.println("Java == java : " + StringUtils.compare("Java", "java"));
System.out.println("Java == null : " + StringUtils.compare("Java", null));
System.out.println("Java == Java : " + StringUtils.compare("Java", "Java"));
System.out.println("null == null : " + StringUtils.compare(null, null));
Complete Code & Output
Method 6: String Comparison Using StringUtils.compareIgnoreCase()
To avoid case-sensitivity issues, use the “StringUtils.compareIgnoreCase()” instead of using the StringUtils.compare() method.
Example: How to Use StringUtils.compareIgnoreCase() in Java
The following code implements the compareIgnoreCase() method on different strings to perform case-insensitive comparisons:
System.out.println("Java == java : " + StringUtils.compareIgnoreCase("Java", "java"));
System.out.println("Java == null : " + StringUtils.compareIgnoreCase("Java", null));
System.out.println("Java == Java : " + StringUtils.compareIgnoreCase("Java", "Java"));
System.out.println("null == null : " + StringUtils.compareIgnoreCase(null, null));
Complete Code & Output
String Comparison Using a User-defined Function
Users can design a custom function to perform the lexicographical string comparison. For instance, create a function named “stringComparison” that accepts two parameters:
public static int stringComparison(String str1, String str2)
Now use the length() method on the given strings to find their length. Store the string size in the integer-type variables:
int str1Size = str1.length();
int str2Size = str2.length();
Use the “Math.min()” to find the minimum string:
int smallString = Math.min(str1Size, str2Size);
Use the for loop to iterate according to the length of the minimum/small string:
for (int i = 0; i < smallString; i++){
Within the body of for-loop, use the charAt() method to find the current character of each string:
char str1CurrentChar = str1.charAt(i);
char str2CurrentChar = str2.charAt(i);
Use the if statement to check if the current characters of each string are equal. If they are not equal, subtract the string2 character from the string1 character and return the resultant value:
if (str1CurrentChar != str2CurrentChar) {
return str1CurrentChar - str2CurrentChar;
}}
After this, check if the length of the given strings is equal. If not, subtract the length of string2 from the length of string1 and return the resultant value:
if (str1Size != str2Size) {
return str1Size - str2Size;
}
If both of the above conditions are not true, this means the given strings are equal, return “0” in that case:
else {
return 0;
}
Now, in the main() method, use the Scanner class to get the strings to be compared from the user:
Scanner obj = new Scanner(System.in);
System.out.println("Please Enter First String: ");
String string1 = obj.next();
System.out.println("Please Enter Second String: ");
String string2 = obj.next();
Finally, invoke the user-defined “stringComparison()” function with the input strings as its arguments to compare the given strings:
System.out.println("is string1 == string2: " + stringComparison(string1, string2));
Review the complete code before execution to avoid unexpected and unwanted results:
package example;import java.util.Scanner;
public class example {
public static int stringComparison(String str1, String str2) {
int str1Size = str1.length();
int str2Size = str2.length();
int smallString = Math.min(str1Size, str2Size);
for (int i = 0; i < smallString; i++) {
char str1CurrentChar = str1.charAt(i);
char str2CurrentChar = str2.charAt(i);
if (str1CurrentChar != str2CurrentChar) {
return str1CurrentChar - str2CurrentChar;
}
}
if (str1Size != str2Size) {
return str1Size - str2Size;
}
else {
return 0;
}
}
public static void main(String args[]) {
Scanner obj = new Scanner(System.in);
System.out.println("Please Enter First String: ");
String string1 = obj.next();
System.out.println("Please Enter Second String: ");
String string2 = obj.next();
System.out.println("is string1 == string2: " + stringComparison(string1, string2));
obj.close();
}
}
Output
The output shows that the user-entered strings are equal:
This is how you can compare strings in Java.
Final Thoughts
In Java, we can perform string comparisons based on the content or reference. To perform reference matching opt for the equality operator “==”. However, to perform string comparison based on content, use the built-in methods like “String.equals()”, “String.compareTo()”, “StringUtils.compare()”, etc. The mentioned method performs case-sensitive string matching.
To perform case-insensitive comparisons, use the IgnoreCase variants of these functions, such as “String.equalsIgnoerCase()”, “StringUtils.compareIgnoreCase()”, etc. The choice of method depends on the users’ needs and preferences.