Can You Tell The Difference Between Equals Method and Equality Operator ( ) in Java?
Can You Tell The Difference Between Equals Method and Equality Operator ( ) in Java?
We are already aware of the (==) equals operator. That we have used this to compare the
equality of the values. But when we talk about the terms of object-oriented programming, we
deal with the values in the form of objects. And this object may contain multiple types of
data. So using the (==) operator does not work in this case. So we need to go with
the .equals() method.
Both [(==) and .equals()] primary functionalities are to compare the values, but the
secondary functionality is different.
So in order to understand this better, let’s consider this with the example -
System.out.println(str1 == str2);
This code will print true. We know that both strings are equals so it will print true. But
here (==) Operators don’t compare each character in this case. It compares the memory
location. And because the string uses the constant pool for storing the values in the memory,
both str1 and str2 are stored at the same memory location.
System.out.println(str1 == str2);
Then in this case, it will print false. Because here no longer the constant pool
concepts are used. Here, new memory is allocated. So here the memory address is
different, therefore ( == ) Operator returns false. But the twist is that the values are
the same in both strings. So how to compare the values? Here the .equals()
method is used.
.equals() method compares the values and returns the result accordingly. If we
modify the above code with -
System.out.println(str1.equals(str2));
equals() ==
This is a method defined in the Object class. It is a binary operator in Java.
The .equals() Method is present in the Object
class, so we can override our custom .equals() It cannot be modified. They always compare
method in the custom class, for objects the HashCode.
comparison.
equals() ==
This operator is used for comparing
This method is used for checking the equality of
addresses (or references), i.e checks if both
contents between two objects as per the
the objects are pointing to the same memory
specified business logic.
location.
Note:
In the cases where the equals method is not overridden in a class, then the class
uses the default implementation of the equals method that is closest to the parent
class.
Object class is considered as the parent class of all the java classes. The
implementation of the equals method in the Object class uses the == operator to
compare two objects. This default implementation can be overridden as per the
business logic