How can I perform string comparison in Java?

Faraz Logo

By Faraz - June 10, 2023

Explore different techniques and methods for performing string comparison in Java. Learn how to compare strings effectively.


To compare strings in Java, you can use the equals() method or the compareTo() method. Here's how you can use each method:

1. equals() method:

The equals() method compares the content of two strings to check if they are equal. It returns a boolean value indicating whether the strings are the same or not.

Example:

String str1 = "Hello";
String str2 = "World";
boolean isEqual = str1.equals(str2);

if (isEqual) {
    System.out.println("The strings are equal.");
} else {
    System.out.println("The strings are not equal.");
}

2. compareTo() method:

The compareTo() method compares two strings lexicographically. It returns an integer value based on the comparison. If the strings are equal, it returns 0. If the first string is lexicographically greater than the second string, it returns a positive value. If the first string is lexicographically smaller, it returns a negative value.

Example:

String str1 = "Apple";
String str2 = "Banana";
int result = str1.compareTo(str2);

if (result == 0) {
    System.out.println("The strings are equal.");
} else if (result < 0) {
    System.out.println("The first string is lexicographically smaller.");
} else {
    System.out.println("The first string is lexicographically greater.");
}
Note that both methods are case-sensitive, so "Hello" and "hello" would be considered different strings. If you want to perform a case-insensitive comparison, you can use the equalsIgnoreCase() method instead of equals().

I hope you found the above information helpful. Please let me know in the comment box if you have an alternate answer πŸ”₯ and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post