Equals is intended to check logical equality and == checks if both references point to same object. (Thanks Sandeep)
a == b;// Compares references, not values.
a.equals(b);// Compares values for equality.
In Core Java, the difference between equals()
and ==
lies in their functionality and what they compare:
equals()
method:equals()
is a method defined in theObject
class, and it is meant to be overridden by classes that need to define specific behavior for object comparison.- The default implementation in the
Object
class compares object references, which means it checks if two object references point to the exact same object in memory. - Many classes in Java override the
equals()
method to provide meaningful comparison based on the content or attributes of objects.
Example:
java
// This will be true, as String class overrides equals() to compare contentString str1 = new String("Hello");
String str2 = new String("Hello");
boolean isEqual = str1.equals(str2);==
operator:- The
==
operator in Java is used for reference comparison when applied to objects. - If used with primitive data types (e.g.,
int
,char
, etc.), it compares the actual values. - When used with objects, it compares the references, checking if both references point to the exact same object in memory.
Example:
java
// This will be false, as it compares references, not contentString str1 = new String("Hello");
String str2 = new String("Hello");
boolean isSameReference = (str1 == str2);- The
In summary, equals()
is meant for content-based comparison and is often overridden by classes to provide meaningful comparisons, while ==
is used for reference comparison, checking if two references point to the exact same object in memory.