Difference between ==  and equals()

Difference between equals() and == is another famous interview question like Why String is final in Java.

Lets check what is the difference by writing some code.

Here we have defined two variables s1 and s2 and both of them carries same value java. Ok, lets try to find out the answer to our question with these two variables. Try to execute the following statement.

Can you predict the output?. It says

So what happens to the ==?. Lets analysis the first two statements we wrote. In that we actually created two String objects s1 and s2 with same value java. So even though those two objects carries same values, their references are not same. In other words, s1 and s2 are located in two different location in memory even though their content are same.

Ok now try with another set of codes.

And try the same checking.

This time we can see that the result as follows

In the above example we didn’t create two separate objects with new String("java"). We just used String literals. So what happens at the second variable creation(that is when line String s4 = "java"; is executed) java used the reference of s3 for s4 also. In other words, both s3 and s4 shares same reference in memory as they are having same value(java) and defined as String literals.

Now you may understand what is the difference between == and equals()?

So simply we can say that == compares the reference of two objects while equals() compares the actual values.
Ok all is fine, but how does the equals method compares the actual values? or who tells them to compare the actual value? The answer is simple, it is implemented in such a way that the actuals values needs to be compared. We can see that implementation in the source code of java.lang.String class. The implementation (jdk 1.7) is given below.

Actually the equals() method is overridden from java.lang.Object.

In several situations we may need to override the equals method like String does above to define equality for our custom classes in our own way.

Leave a Comment

Your email address will not be published. Required fields are marked *