Google News
logo
Java Program to Differentiate String == operator and equals() method
In Java, the == operator and the equals() method are used to compare strings, but they have different behaviors. Here's an example program that illustrates the difference :
Program :
public class StringCompare {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = new String("Hello");
        
        // Using == operator
        System.out.println("Using == operator:");
        System.out.println(str1 == str2); // true
        System.out.println(str1 == str3); // false
        
        // Using equals() method
        System.out.println("\nUsing equals() method:");
        System.out.println(str1.equals(str2)); // true
        System.out.println(str1.equals(str3)); // true
    }
}
Output :
Using == operator:
true
false

Using equals() method:
true
true
We define three strings str1, str2, and str3. str1 and str2 have the same value, while str3 is a new string with the same value as str1.

When we use the == operator to compare strings, it checks if the two strings are the same object. In other words, it checks if they have the same memory address.

In the example above, str1 and str2 have the same memory address because they are both literals, so str1 == str2 returns true. However, str1 and str3 have different memory addresses because str3 is a new object created using the new keyword, so str1 == str3 returns false.

When we use the equals() method to compare strings, it checks if the two strings have the same value. In the example above, str1 and str2 have the same value, so str1.equals(str2) returns true. str1 and str3 also have the same value, so str1.equals(str3) returns true.

Therefore, we should use the equals() method to compare strings when we want to check if they have the same value, and use the == operator to check if they are the same object.