Difference between equals() and == in java

In this post, we will see about the difference between equals and == in java.

This is most asked java interview question for fresher or 2-year experienced java developer and it might be confusing sometimes. Let’s try to understand each quickly.


Equality operator “==”

Equality operator can be used to compare primitives but when you compare objects using ==, it just compares reference not the actual content of the objects.


Equals methods

If you want to compare the actual content of the object, then you need to override equals method in your class. If you do not override object’s class equals method, then it behaves same as "==" and compares references only.

Let’s understand difference between equals() and == in java.


Difference between equals() and == in java

  • == is operator whereas equals is method in java.
  • == is recommended to compare primitives whereas equals method is recommended to compare the actual content of objects.
  • Equals method can be overridden but you can’t override behavior of “==” operator
  • == can be used with primitives and objects but you can’t use equals method with primitives.

Let’s take quick example in case of String and custom object.


Example

Equals and == in case of String

String is most common scenario where equals and == methods are used.

When you run above program, you will get below output

false
true
===================
true
true

Equals and == in case of Custom objects

It is very much similar to String. Let’s create Employee class and override equals method. If two employees have same name and age then they will be considered as same.

Create another class for Employee comparison

When you run above program, you will get below output

false
true
===================
true
true

That’s all about difference between equals() and == in java.

Was this post helpful?

Leave a Reply

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