BM Balmiki Mandal 06 May 2023 17 views 0 comments Core Java

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 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.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023