In this article, we will discuss different ways to compare String in Java. For example, we can use equals() and equalsIgnoreCase() for equality check and compare() and compareTo() for ordering comparison. we can even use the equality operator == to perform reference based comparison e.g. to check both the String reference variable points to the same object.
- Using equals() Method
- Using equalsIgnoreCase() Method
- Using compareTo() and compareToIgnoreCase() Method
- Using == Operator
- Using contentEquals() Method
Important: Always use equals() if you are checking for equality because it does a value-based comparison.
1. Using equals() Method
If you just want to check if two string is same i.e. they are of the same case, contains the same characters and in the same sequence then you should use equals() method.
The equals() method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Here is an example of using equals() to compare String in Java:
package net.javaguides.examples;
public class EqualsExample {
public static void main(String[] args) {
String str = "javaguides";
String str1 = "javaguides";
String str3 = "javatutorial";
boolean equal = str.equals(str1);
System.out.println(" Is both string are equal :: " + equal);
}
}
Output:
Is both string are equal :: true
I would suggest this approach to check equality of two string objects.
2. Using equalsIgnoreCase() Method
Use equalsIgnoreCase() method, if you want to compare two string objects and ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are the equal ignoring case.
The equals() method does case-sensitive comparison e.g. "Java" and "java" will not be considered equal if you use equals() method but if you treat them same i.e. you perform case-insensitive comparison then you should use equalsIgnoreCase() method.
Here is code sample to demonstrate usage of equalsIgnoreCase() Method:
package net.javaguides.examples;
public class EqualsIgnoreCaseExample {
public static void main(String[] args) {
String str = "javaguides";
boolean equal = str.equalsIgnoreCase("JAVAguides");
System.out.println("Strings are equal :: " + equal);
}
}
Output:
Strings are equal :: true
3. Using compareTo() and compareToIgnoreCase() Method
compareTo() Method
The compareTo() method is used to compare String on alphabetic or alphanumeric order, precisely known as a lexicographical order. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string.
It has this general form:
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the comparison is returned as values meaning:
- Less than zero - The invoking string is less than str.
- Greater than zero - The invoking string is greater than str.
- Zero - The two strings are equal.
package net.javaguides.examples;
public class CompareToExample {
public static void main(String[] args) {
String s1 = "Hello World";
String s2 = "Hello World";
String s3 = "Java";
String s4 = "Guides";
System.out.println(s1.compareTo(s2));
// 0 because both are equal
System.out.println(s1.compareTo(s3));
// -2 because "H" is 2 times lower than "J"
System.out.println(s1.compareTo(s4));
// 1 because "G" is 1 times greater than "H"
}
}
Output:
0
-2
1
compareToIgnoreCase() Method
Compares two strings lexicographically, ignoring case differences. This method returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase(Character.toUpperCase(character)) on each character.
package net.javaguides.examples;
public class CompareToIgnoreCaseExample {
public static void main(String[] args) {
String s1 = "Hello World";
String s2 = "hello world";
String s3 = "Java";
String s4 = "java";
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s3.compareToIgnoreCase(s4));
}
}
Output:
0
0
4. Using == Operator
Don't use == operator for String comparison because it checks if two string variable pointing to the same object or not. Always use equals() method to check two string objects value or content comparison.
I added this approach in this article because I want to discourage Java developers from using the == operator for comparing String.
Here is an example to demonstrates the usage of == operator:
package net.javaguides.examples;
public class EqualOperatorExample {
public static void main(String[] args) {
String s1 = "javaguides";
String s2 = new String("javaguides");
String s3 = "javaguides";
boolean result = s1 == s2;
boolean result2 = s1 == s3;
System.out.println(" Result :: " + result);
System.out.println(" Result of === operator :: " + result2);
}
}
Output:
Result :: false
Result of === operator :: true
5. Using contentEquals() Method
Compares this string to the specified CharSequence. The result is true if and only if this String represents the same sequence of char values as the specified sequence.
package net.javaguides.examples;
public class ContentEqualsExample {
public static void main(String[] args) {
String str = "javaguides";
String subStr = "javaguides";
boolean isContentEquals = str.contentEquals(subStr);
System.out.println("isContentEquals :: " + isContentEquals);
isContentEquals = str.contentEquals(new StringBuffer(subStr));
System.out.println("isContentEquals :: " + isContentEquals);
}
}
Output:
isContentEquals :: true
isContentEquals :: true
Important Point
Now that we know multiple ways to perform String comparison in Java, let me share you some important points and useful tips and trick you can follow while comparing strings in Java.
- Always use equals() if you are checking for equality because it does a value-based comparison.
- Use equalsIgnoreCase() for case-insensitive equality check.
- Don't use == to compare String in Java. It performs reference equality check and only returns true if both String point to the same object. Which means even if the content of two String is same == may return false if they point to different objects.
- Use compareTo() for alphabetic comparison for String objects. When you override compareTo() method, make sure that it follows its contract with equals() method i.e it should return zero when two objects are equal with equals() method.
Kindly leave a comment if you know any other way to compare String objects in Java.
You should check out below String handling articles:
- Guide to Java String Constant Pool
- Java String Methods with Examples
- Guide to String Best Practices in Java (Best Practice)
- String Special Operations with Examples
- String Comparison Methods with Examples
- String Methods for Character Extraction
- String Searching Methods with Examples
- String Modifying Methods with Examples
- Java StringBuffer Class API Guide
- StringBuilder Class Methods in Java
- StringBuffer Class Methods in Java
- Java StringBuilder Class API Guide
- Java 8 StringJoiner Class
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course