Comparing == Operator and equals() Method in Java
Difference Between == and equals() in Java
The difference between == and .equals()
in Java is a common source of confusion for many developers. The reason for this discrepancy is primarily due to the way these two operators are defined in the language. In this article, we’ll take a look at both of these operators and the differences between them.
What is == Operator?
The double equals operator (==
) is a comparison operator used to compare two values. It will return true
if both operands are equal and false
if they’re different. Here’s an example:
int x = 5;
int y = 5;
System.out.println(x == y); // Prints true
What is .equals() Method?
.equals()
is a method provided by the Object
class (the parent class of all Java classes) used to compare the given object with that of the specified object. The comparison is done based on the content instead of the reference address. Here’s an example:
String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1.equals(s2)); // Prints true
Differences Between == and .equals()
- Performance: The
==
operator is faster than.equals()
as the former does not perform any type of conversion. - Type Safety: The
==
operator should only be used to compare primitive types. As for the.equals()
method, it can be used to compare both primitive types and reference variables. - Null Safety: The
==
operator throwsNullPointerException
if one or both operands arenull
. Whereas, the.equals()
method will returnfalse
when one operand isnull
and only returnstrue
if both operands are notnull
.
Conclusion
Comparing two objects using the ==
operator checks for reference equality, whereas .equals()
checks for value equality. Therefore, the .equals()
method should be used to compare two objects, while the ==
operator should only be used to compare primitives such as int, float, char etc. It should not be used to compare objects unless you are sure about the behavior.