Java program to differentiate string == operator and equals() method

htt‮‬ps://www.theitroad.com

In Java, the == operator and the equals() method are both used to compare strings, but they have different behaviors.

The == operator tests whether two string references point to the same object in memory, while the equals() method tests whether the contents of the two strings are the same.

Here's a Java program that demonstrates the difference between the == operator and the equals() method:

public class Main {
    public static void main(String[] args) {
        String s1 = "Hello";
        String s2 = "Hello";
        String s3 = new String("Hello");

        System.out.println("s1 == s2: " + (s1 == s2)); // true
        System.out.println("s1.equals(s2): " + s1.equals(s2)); // true

        System.out.println("s1 == s3: " + (s1 == s3)); // false
        System.out.println("s1.equals(s3): " + s1.equals(s3)); // true
    }
}

In this program, we create three String objects: s1 and s2 are created using string literals, while s3 is created using the new operator.

We then use the == operator and the equals() method to compare these strings. The first comparison, s1 == s2, returns true because s1 and s2 both point to the same string object in memory. The second comparison, s1.equals(s2), also returns true because the contents of the two strings are the same.

The third comparison, s1 == s3, returns false because s1 and s3 point to different string objects in memory, even though they contain the same characters. The fourth comparison, s1.equals(s3), returns true because the contents of the two strings are the same.

It's important to remember that the == operator and the equals() method are not interchangeable. When comparing strings for equality, you should use the equals() method, not the == operator.