Comparing == Operator and equals() Method in Java

06 May 2023 Balmiki Mandal 0 Core 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 throws NullPointerException if one or both operands are null. Whereas, the .equals() method will return false when one operand is null and only returns true if both operands are not null.

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.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.