Write a Java Program to Compare Strings

As a Java programmer, you may often need to compare two strings to check if they are equal or not.

In this tutorial, we will discuss how to compare strings in Java using different methods.


Using the equals() method

The easiest way to compare two strings in Java is to use the equals() method.

This method compares the content of two strings and returns true if they are equal and false if they are not.

Here’s an example:

String str1 = "hello";
String str2 = "world";
if (str1.equals(str2)) {
    System.out.println("Strings are equal");
} else {
    System.out.println("Strings are not equal");
}

Output: Strings are not equal

Using the equalsIgnoreCase() method

The equalsIgnoreCase() method is similar to the equals() method, but it ignores the case of the strings being compared.

This means that if the strings have different cases, but the same content, they will still be considered equal.

Here’s an example:

String str1 = "Hello";
String str2 = "hello";
if (str1.equalsIgnoreCase(str2)) {
    System.out.println("Strings are equal");
} else {
    System.out.println("Strings are not equal");
}

Output: Strings are equal

Using the compareTo() method

The compareTo() method compares two strings lexicographically (i.e., in dictionary order).

It returns a positive integer if the first string is greater than the second string, a negative integer if the first string is smaller than the second string, and zero if they are equal.

Here’s an example:

String str1 = "hello";
String str2 = "world";
int result = str1.compareTo(str2);
if (result == 0) {
    System.out.println("Strings are equal");
} else if (result > 0) {
    System.out.println("First string is greater");
} else {
    System.out.println("Second string is greater");
}

Output: Second string is greater


Conclusion

In Java, you can compare strings using the equals() method, the equalsIgnoreCase() method, and the compareTo() method.

These methods are simple and easy to use and can help you determine whether two strings are equal or not.