The equals() method checks whether two objects are equal.
Example
Syntax of Object equals()
The syntax of the equals() method is:
object.equals(Object obj)
equals() Parameters
The equals() method takes a single parameter.
- obj - object which is to be compared with the current object
equals() Return Values
- returns
trueif two objects are equal - returns
falseif two objects are not equal
Note: In Java, if two reference variables refer to the same object, then the two reference variables are equal to each other.
Example 1: Java Object equals()
In the above examples, we have created objects of the Object class. Here, the equals() method is used to check if objects are equal to each other.
Example 2: Object equals() With String
In the above example, we have used the equals() method to check if two objects obj1 and obj2 are equal.
Here, initially, both the newly created objects are null. Hence, the method returns true. However, when we assigned values to the objects. The method returns false.
It is because the String class overrides the equal() method so that the method compares the element of the object. Since the values of obj1 and obj2 are different, the method returns false.
Note: The Object class is the superclass for all the classes in Java. Hence, every class and arrays can implement the equals() method.