Comparing strings in Java involves checking whether two strings are equal or determining their relative ordering. The String class in Java provides several methods for comparison, each designed for specific use cases.
Ways to Compare Strings in Java
1. Using == Operator
The == operator checks whether two string references point to the same memory location (i.e., whether they are the same object).
Example:
String str1 = “Hello”;
String str2 = “Hello”;
String str3 = new String(“Hello”);
System.out.println(str1 == str2); // true (both point to the same object in the string pool)
System.out.println(str1 == str3); // false (str3 is a new object)
Characteristics:
- Compares references, not content.
- Only true if both strings are interned (from the string pool).
2. Using equals() Method
The equals() method checks whether two strings have the same content.
Syntax:
boolean result = str1.equals(str2);
Example:
String str1 = “Hello”;
String str2 = new String(“Hello”);
System.out.println(str1.equals(str2)); // true (content is the same)
Characteristics:
- Case-sensitive comparison.
- Returns true if both strings have identical characters in the same order.
3. Using equalsIgnoreCase() Method
This method compares strings ignoring case differences.
Syntax:
boolean result = str1.equalsIgnoreCase(str2);
Example:
String str1 = “hello”;
String str2 = “Hello”;
System.out.println(str1.equalsIgnoreCase(str2)); // true (ignores case)
Characteristics:
- Case-insensitive.
- Useful when case is not important (e.g., user input validation).
4. Using compareTo() Method
The compareTo() method compares two strings lexicographically, based on Unicode values of characters.
Syntax:
int result = str1.compareTo(str2);
Example:
String str1 = “Apple”;
String str2 = “Banana”;
System.out.println(str1.compareTo(str2)); // Negative value (str1 < str2)
Characteristics:
- Returns:
- 0 if the strings are equal.
- Negative value if str1 is lexicographically less than str2.
- Positive value if str1 is lexicographically greater than str2.
- Case-sensitive.
5. Using compareToIgnoreCase() Method
Similar to compareTo(), but it ignores case differences.
Syntax:
int result = str1.compareToIgnoreCase(str2);
Example:
String str1 = “apple”;
String str2 = “Apple”;
System.out.println(str1.compareToIgnoreCase(str2)); // 0 (ignores case)
6. Using regionMatches() Method
The regionMatches() method compares specific parts of two strings.
Syntax:
boolean result = str1.regionMatches(start1, str2, start2, length);
Example:
String str1 = “HelloWorld”;
String str2 = “WorldHello”;
System.out.println(str1.regionMatches(5, str2, 0, 5)); // true (matches “World”)
Characteristics:
- Case-sensitive by default, but can be made case-insensitive by passing true as the first argument.
7. Using contentEquals() Method
The contentEquals() method checks whether the string matches the content of a CharSequence.
Syntax:
boolean result = str1.contentEquals(charSequence);
Example:
String str1 = “Hello”;
StringBuffer sb = new StringBuffer(“Hello”);
System.out.println(str1.contentEquals(sb)); // true
Characteristics:
- Compares String with StringBuffer or StringBuilder.
8. Using matches() Method
The matches() method checks if the string matches a specified regular expression.
Syntax:
boolean result = str1.matches(regex);
Example:
String str = “Hello123”;
System.out.println(str.matches(“[A-Za-z]+\\d+”)); // true
Characteristics:
- Useful for pattern matching (e.g., validating email formats).
Case Sensitivity in Comparisons
Method | Case-Sensitive | Case-Insensitive |
== | Yes | No |
equals() | Yes | No |
equalsIgnoreCase() | No | Yes |
compareTo() | Yes | No |
compareToIgnoreCase() | No | Yes |
regionMatches() | Yes (by default) | Yes (with option) |
Performance Considerations
- Use == when you need to check if two strings are the same object (not content).
- Use equals() for most general-purpose content comparisons.
- Use compareTo() for sorting or ordering strings.
- Avoid matches() for simple comparisons as regular expressions can be slow.
Common Mistakes
- Using == instead of equals():
String str1 = new String(“Hello”);
String str2 = new String(“Hello”);
System.out.println(str1 == str2); // false (different objects)
System.out.println(str1.equals(str2)); // true (same content)
- Ignoring case unintentionally: Use equalsIgnoreCase() or compareToIgnoreCase() when case-insensitive comparison is required.
Example Code
public class StringComparison {
public static void main(String[] args) {
String str1 = “Java”;
String str2 = “java”;
String str3 = “Programming”;
// Using equals
System.out.println(“equals: ” + str1.equals(str2)); // false
// Using equalsIgnoreCase
System.out.println(“equalsIgnoreCase: ” + str1.equalsIgnoreCase(str2)); // true
// Using compareTo
System.out.println(“compareTo: ” + str1.compareTo(str3)); // Negative value
// Using compareToIgnoreCase
System.out.println(“compareToIgnoreCase: ” + str1.compareToIgnoreCase(str2)); // 0
// Using regionMatches
System.out.println(“regionMatches: ” + str1.regionMatches(true, 0, str2, 0, 4)); // true
}
}
Output:
equals: false
equalsIgnoreCase: true
compareTo: -6
compareToIgnoreCase: 0
regionMatches: true
Conclusion
Choosing the right method to compare strings depends on your requirements:
- Use equals() or equalsIgnoreCase() for equality.
- Use compareTo() or compareToIgnoreCase() for ordering.
- Use matches() for pattern matching. Understanding these distinctions will help avoid bugs and improve the clarity of your code.