Java
Programming
String Comparison
Coding
Software Development

How do I compare strings in Java?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Comparing strings in Java is a fundamental task in many Java applications whether you're sorting data, validating inputs, or carrying out any operation that requires comparison of two or more strings. Due to the nature of strings in Java, there are several methods to accomplish this, each with its own use case and nuances.

Understanding Java Strings

In Java, strings are objects managed by the String class. This setup is crucial because it means that strings are not just mere sequences of characters as seen in some other programming languages, but instances of a class with methods and properties.

Ways to Compare Strings in Java

1. Using the equals() Method

The equals() method checks if two strings have the exact same sequence of characters:

java
1String str1 = "Hello";
2String str2 = "Hello";
3String str3 = "hello";
4
5boolean result1 = str1.equals(str2);  // true
6boolean result2 = str1.equals(str3);  // false

This method is case-sensitive and does not consider string case while comparing.

2. Using the equalsIgnoreCase() Method

Java provides the equalsIgnoreCase() method to compare two strings regardless of their case:

java
1String str1 = "hello";
2String str2 = "HELLO";
3
4boolean result = str1.equalsIgnoreCase(str2);  // true

This method is very useful in scenarios where you want to perform comparisons devoid of case sensitivity, like user input validations.

3. Using the compareTo() Method

The compareTo() method compares two strings lexicographically and returns an integer:

java
1String str1 = "apple";
2String str2 = "banana";
3String str3 = "apple";
4
5int result1 = str1.compareTo(str2);  // < 0
6int result2 = str1.compareTo(str3);  // = 0
7int result3 = str2.compareTo(str1);  // > 0
  • A result < 0 indicates that str1 is lexicographically less than str2.
  • A result = 0 indicates that both strings are equal.
  • A result > 0 indicates str1 is greater.

4. Using the compareToIgnoreCase() Method

Similar to compareTo(), but ignoring character case:

java
1String str1 = "Apple";
2String str2 = "apple";
3
4int result = str1.compareToIgnoreCase(str2);  // 0

Special Cases When Comparing Strings

  1. Null Strings: Comparing strings where one or both strings are null can lead to NullPointerException. Safe comparison necessitates null checks.
  2. Pool of Interned Strings: The Java String Pool — a storage area in Java heap — holds literal strings. Because of String interning, two strings having the same characters can point to the same memory location if they are interned.
  3. String concatenation: Keep in mind that modifying one string which another is referenced to, doesn't affect the other string due to string immutability.

Best Practices

  • Use equals() and equalsIgnoreCase() for comparing equality.
  • Use compareTo() and compareToIgnoreCase() for sorting or when lexical ordering is required.
  • Always check for null to avoid NullPointerException.

Summary Table

MethodCase SensitiveReturn TypeUse Case
equals(Object anObject)YesbooleanCheck if two strings are exactly the same.
equalsIgnoreCase(String anotherString)NobooleanCheck equality ignoring case differences.
compareTo(String anotherString)Yesint (negative, zero, positive)Lexicographically compare two strings.
compareToIgnoreCase(String str)Noint (negative, zero, positive)Lexical comparison ignoring case.

Using the right string comparison method not only ensures correctness in your Java application but also enhances security and performance, especially in data-sensitive and high-load applications.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.