Java Object equals() Method
The Object equals() method is used to compare two objects for equality.
The equals() method compares two objects to determine if they reference the same object, i.e., it checks if the memory addresses of the two objects are the same.
Note: If a subclass overrides the equals() method, it must also override the hashCode() method. For example, the String class overrides the equals() method and also the hashCode() method.
Syntax
object.equals(Object obj)
Parameters
- obj - The object to compare.
Return Value
Returns true if the objects are equal, otherwise returns false.
Example
The following example demonstrates the use of the equals() method:
Example
class tutorialproTest {
public static void main(String[] args) {
// Object class using equals() method
// Create two objects
Object obj1 = new Object();
Object obj2 = new Object();
// Check if obj1 and obj2 are equal
// Different objects, different memory addresses, not equal, returns false
System.out.println(obj1.equals(obj2)); // false
// Assign obj1 to obj3
// String overrides the equals() method
// Object reference, same memory address, equal, returns true
Object obj3 = obj1;
System.out.println(obj1.equals(obj3)); // true
}
}
The output of the above program is:
false
true
The String class overrides the equals() method to compare two strings for equality:
Example
class tutorialproTest {
public static void main(String[] args) {
// String class using equals() method
// Create two objects
String obj1 = new String();
String obj2 = new String();
// Check if obj1 and obj2 are equal
// Both objects are initialized to null, so they are equal, returns true
System.out.println(obj1.equals(obj2)); // true
// Assign values to the objects
obj1 = "tutorialpro";
obj2 = "Google";
// Check if obj1 and obj2 are equal
// The two values are different, different memory addresses, not equal, returns false
System.out.println(obj1.equals(obj2)); // false
}
}
The output of the above program is:
true
false