Comparing strings in JAVA

In Java Programming language, There are two ways by which we can compare strings in java.

  1. By using equals() method.
  2. By using == operator.

Compare String using equal method in java

We can make use the equals() method to compare two strings. The equals() is an in-built method that is defined in the String class and only returns Boolean value (true/false) which indicating whether the given two strings are equal or not equal.

Below is an Example on How to use equals() method to compare two strings:

String str1 = "hello";
String str2 = "hello";

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

Compare String using == operator in java

An Alternatively way, we can use the == operator to compare two strings. But note that this == will compares the references of the two strings rather than the contents of the strings themselves. As a result, it may not always produce the desired result.

Here’s an example of how to use the == operator to compare two strings:

String str1 = "hello";
String str2 = "hello";

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

In most of cases it is recommended to better use equals() method for comparing strings in java, because it always compares the contents instead of references.