Java String Compare: A Guide to Effective String Comparison in Java

Java String Compare: A Guide to Effective String Comparison in Java

8 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Apr 18, 2024 14:14 IST

Have you ever wondered how to compare strings in Java? You can use various methods for that, like using equals(), using == Operator, using equalsIgnoreCase(), using compareTo(), and using compareToIgnoreCase(). Let's understand more!

String comparison is a common operation in programming for various reasons like determining equality or ordering of text data, searching for specific substrings within larger text, sorting strings alphabetically and validating input or checking for specific patterns in text. There are various methods to compare strings in Java, depending on the requirements of the comparison. In this blog, we will learn about all those methods one by one!

Table of Content

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
6 weeks
β‚Ή15 K
3 months
β‚Ή2.05 K
3 months
– / –
170 hours
β‚Ή5.4 K
1 month
– / –
2 months
– / –
6 months
β‚Ή5.5 K
1 month
β‚Ή17 K
3 months

1. Using equals()

The equals() method is used to compare two strings for content equality.

Syntax

boolean result = string1.equals(string2);

Here, string1 and string2 are the two string objects you want to compare.
The method returns a boolean value, true if the strings are equal and false if they are not.

Characteristics

  • Case-sensitive: It considers the case of the characters (uppercase and lowercase are treated as different).
  • Content Comparison: It compares the actual contents of the strings, not their memory addresses.

Example


 
public class StringEqualsExample {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "Java";
String str3 = "JAVA";
// Comparing str1 and str2
if (str1.equals(str2)) {
System.out.println("str1 and str2 are equal."); // This will be printed
} else {
System.out.println("str1 and str2 are not equal.");
}
// Comparing str1 and str3
if (str1.equals(str3)) {
System.out.println("str1 and str3 are equal.");
} else {
System.out.println("str1 and str3 are not equal."); // This will be printed
}
}
}
Copy code

Output

str1 and str2 are equal.
str1 and str3 are not equal.

  • str1.equals(str2) returns true because both str1 and str2 contain the same characters in the same order ("Java").
  • str1.equals(str3) returns false because, although str1 and str3 contain the same letters, the case of the letters is different (uppercase vs. lowercase), and equals() is case-sensitive.

This example demonstrates how to use the equals() method to compare strings in Java. The method is commonly used in situations where you need to check if two strings are exactly the same in terms of their content, taking letter cases into account.

 

2. Using == Operator

The == operator in Java is used to compare the references of objects, not their content. When used with strings, it checks whether both string variables point to the same memory location, not whether they have the same characters.

Characteristics

  • Reference Comparison: It checks if both string references point to the same object in the memory.
  • Not Reliable for Content Comparison: Two strings with the same content might have different references.

Example


 
public class StringReferenceComparison {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
// Comparing str1 and str2 with ==
if (str1 == str2) {
System.out.println("str1 and str2 refer to the same object."); // This will be printed
} else {
System.out.println("str1 and str2 refer to different objects.");
}
// Comparing str1 and str3 with ==
if (str1 == str3) {
System.out.println("str1 and str3 refer to the same object.");
} else {
System.out.println("str1 and str3 refer to different objects."); // This will be printed
}
}
}
Copy code

Output

str1 and str2 refer to the same object.
str1 and str3 refer to different objects.

  • str1 == str2 returns true because both str1 and str2 are string literals. In Java, string literals with the same content are stored in the same memory location in the string pool. Thus, they refer to the same object.
  • str1 == str3 returns false because str3 is created using a new String("Hello"), which forces Java to create a new string object in the memory, even though the content is the same as str1.

The == operator should not be used for content comparison in strings. Instead, it's used to compare the actual references of the objects. For content comparison, always use .equals()

3. Using equalsIgnoreCase()

The equalsIgnoreCase() method in Java is used to compare two strings for equality, ignoring their case (uppercase or lowercase). It's useful when you want to check if two strings are the same regardless of whether they are written in uppercase, lowercase, or a combination thereof.

Syntax

boolean result = string1.equalsIgnoreCase(string2);

Here, string1 and string2 are the two string objects to be compared.
Returns true if the strings are equal (ignoring case) and false otherwise.

Characteristics

  • Case-insensitive Comparison: It compares the content of strings without considering the case.
  • Content Comparison: Like equals(), it compares the actual contents of the strings.

Example


 
public class StringComparisonIgnoreCase {
public static void main(String[] args) {
String str1 = "Java Programming";
String str2 = "java programming";
String str3 = "JAVA";
// Comparing str1 and str2
if (str1.equalsIgnoreCase(str2)) {
System.out.println("str1 and str2 are equal regardless of case."); // This will be printed
} else {
System.out.println("str1 and str2 are not equal.");
}
// Comparing str1 and str3
if (str1.equalsIgnoreCase(str3)) {
System.out.println("str1 and str3 are equal regardless of case.");
} else {
System.out.println("str1 and str3 are not equal regardless of case."); // This will be printed
}
}
}
Copy code

Output

str1 and str2 are equal regardless of case.
str1 and str3 are not equal regardless of case.

  • str1.equalsIgnoreCase(str2) returns true because both strings are the same when case differences are ignored.
  • str1.equalsIgnoreCase(str3) returns false because, even when ignoring case, the contents of str1 and str3 are not the same.

Use equalsIgnoreCase() when you need to compare strings for equality without considering their case. This method is particularly useful in scenarios where case sensitivity is not important, such as comparing user input in a case-insensitive context.

4. Using compareTo()

The compareTo() method in Java is used for lexicographical comparison between two strings. It compares strings based on the Unicode value of each character in the strings.

Syntax

int result = string1.compareTo(string2);

Here, string1 and string2 are the two string objects to be compared.
Returns:

  • A positive number if string1 is lexicographically greater than string2.
  • 0 if string1 and string2 are lexicographically equal.
  • A negative number if string1 is lexicographically less than string2.

Characteristics

  • Case-Sensitive: The comparison is sensitive to the case of the characters.
  • Lexicographical Order: Based on the Unicode value of each character.

Example


 
public class StringComparisonUsingCompareTo {
public static void main(String[] args) {
String str1 = "Apple";
String str2 = "Banana";
String str3 = "Apple";
// Comparing str1 and str2
int result1 = str1.compareTo(str2);
System.out.println("Comparing Apple and Banana: " + result1); // Will print a negative number
// Comparing str1 and str3
int result2 = str1.compareTo(str3);
System.out.println("Comparing Apple and Apple: " + result2); // Will print 0
// Comparing str2 and str1
int result3 = str2.compareTo(str1);
System.out.println("Comparing Banana and Apple: " + result3); // Will print a positive number
}
}
Copy code

Output

Comparing Apple and Banana: -1
Comparing Apple and Apple: 0
Comparing Banana and Apple: 1

  • str1.compareTo(str2) returns a negative number because "Apple" is lexicographically less than "Banana".
  • str1.compareTo(str3) returns 0 because both strings are lexicographically equal.
  • str2.compareTo(str1) returns a positive number because "Banana" is lexicographically greater than "Apple".

Use compareTo() for sorting strings or when you need to know not just whether strings are equal but also which one comes first in lexicographical order. Remember that this method is case-sensitive.

5. Using compareToIgnoreCase()

The compareToIgnoreCase() method in Java performs a lexicographical comparison between two strings, ignoring case differences. It's used to determine the ordering of strings in a case-insensitive manner.

Syntax

int result = string1.compareToIgnoreCase(string2);

Here, string1 and string2 are the string objects to be compared.
Returns:

  • A positive number if string1 is lexicographically greater than string2, ignoring case.
  • 0 if string1 and string2 are equal, ignoring case.
  • A negative number if string1 is lexicographically less than string2, ignoring case.

Characteristics

  • Case-Insensitive: The comparison does not consider the case of the characters.
  • Lexicographical Order: Comparison is based on the Unicode value of each character, similar to compareTo(), but case is ignored.

Example


 
public class StringComparisonUsingCompareToIgnoreCase {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";
String str3 = "world";
// Comparing str1 and str2
int result1 = str1.compareToIgnoreCase(str2);
System.out.println("Comparing Hello and hello: " + result1); // Will print 0
// Comparing str1 and str3
int result2 = str1.compareToIgnoreCase(str3);
System.out.println("Comparing Hello and world: " + result2); // Will print a negative number
// Comparing str3 and str1
int result3 = str3.compareToIgnoreCase(str1);
System.out.println("Comparing world and Hello: " + result3); // Will print a positive number
}
}
Copy code

Output

Comparing Hello and hello: 0
Comparing Hello and world: -15
Comparing world and Hello: 15

  • str1.compareToIgnoreCase(str2) returns 0 because "Hello" and "hello" are considered equal when ignoring case.
  • str1.compareToIgnoreCase(str3) returns a negative number because "Hello" comes before "world" in lexicographical order when ignoring case.
  • str3.compareToIgnoreCase(str1) returns a positive number because "world" comes after "Hello" in lexicographical order when ignoring case.

Use compareToIgnoreCase() when you need to sort strings or compare their ordering in a case-insensitive manner. This method is useful when the case of the strings should not affect their comparison, such as in alphabetical listings where case is irrelevant.

Array Programs in Java | Beginner to Expert Level

A Guide to Power Function in Java

Getting Started with Java Hello World Program

Java Comments | About, Types and Examples

Understanding Variables in Java

A Guide to Java Math Class

What are Identifiers in Java?

Thus, there are several methods and approaches for comparing two strings, each with its own characteristics and use cases. Choose the appropriate method based on your specific requirements.

Check out Java courses here!

FAQs

What is String comparison in Java, and why is it important?

String comparison in Java involves determining whether two strings are equal or determining their relative order based on lexicographic (dictionary) ordering. It's crucial for various tasks, such as searching, sorting, and data validation.

What are the different methods available for comparing strings in Java?

Java offers several methods for comparing strings, including equals(), equalsIgnoreCase(), compareTo(), compareToIgnoreCase(), startsWith(), endsWith(), and contains(). Each method serves a specific purpose and can be used depending on the requirements of the comparison.

How does equals() differ from compareTo() in Java String comparison?

The equals() method checks if two strings have the same content, returning true if they are equal and false otherwise. In contrast, the compareTo() method compares strings lexicographically and returns an integer value indicating their relative order (negative, zero, or positive).

What precautions should be taken when comparing strings for equality in Java?

When comparing strings for equality in Java, it's essential to handle null values gracefully using null-safe methods like Objects.equals() or by explicitly checking for null. Additionally, consider using equalsIgnoreCase() when case-insensitive comparison is required.

Are there any performance considerations to keep in mind when comparing strings in Java?

When comparing strings for equality, be cautious with the use of the == operator, as it compares references, not the actual content of strings. For performance-sensitive applications, consider using methods like equals() or compareTo() for accurate string comparison.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio