0 votes
1 view
in Java by (4.1k points)

I wanted to clarify if I understand this correctly:

  • == -> is a reference comparison, i.e. both objects point to the same memory location

  • .equals() -> evaluates to the comparison of values in the objects

Am I correct in my understanding ?

1 Answer

0 votes
by (46.1k points)

Yes, you are right but let me brief you with some more points for better understanding:

The main difference between .equals() method and == operator is that one is method and the other is the operator.

We can use == operators for reference observation (address comparison) and  .equals() method for content observation . In simple words, == verify if both objects point to the same memory location. On the other hand, equals() evaluates the observation of values in the objects.

If a class doesn't override the equals method, then by default it uses equals(Object o) method of the most imminent parent class that has revoked this method. 

Here's an example:


public class Test { 

    public static void main(String[] args) 


        String s1 = new String("HELLO"); 

        String s2 = new String("HELLO"); 

        System.out.println(s1 == s2); 






Description: Here we are building two objects namely s1 and s2.

Both s1 and s2 point to different objects.

When we use == operator for s1 and s2 observation then the result is false as both have different addresses in memory.

Using equals, the result is true as it's only associating the values given in s1 and s2.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !