Can you tell the difference between equals() method and equality operator (==) in Java?
Yes, in Java, the equals()
method and the equality operator (==
) serve different purposes and are used in different contexts when comparing objects.
==
Operator==
operator is used to compare the references of two objects. It checks whether both references point to the same object in memory.int
, char
, etc.), ==
compares the actual values.Example:
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2); // false, because str1 and str2 refer to different objects
equals()
Methodequals()
method is intended to compare the actual content or state of two objects. By default, it behaves like ==
, comparing references, but it can be overridden in a class to provide a meaningful comparison based on the object's attributes.String
, Integer
, etc.) override the equals()
method to provide value-based equality.Example:
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2)); // true, because str1 and str2 have the same content
==
when you want to check if two references point to the same object.equals()
when you want to check if two objects are logically equivalent (i.e., have the same content).When overriding the equals()
method, it is also a good practice to override the hashCode()
method to maintain the general contract for the hashCode()
method, which states that equal objects must have the same hash code.