Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k 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 (46k 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:

Input:

public class Test { 

    public static void main(String[] args) 

    { 

        String s1 = new String("HELLO"); 

        String s2 = new String("HELLO"); 

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

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

    } 

Output:

false

true

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.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...