Understanding the equals() Method in Java.

In Java, the equals method present inside Object class, and it is used to compare the equality of two objects. If our class doesn’t contain .equals() method then Object class .equals() method will be executed which is always meant for reference comparison (address comparison). If two references pointing to the same object then only .equals() method returns true. Based on our programming requirement we can override .equals() method for content comparison purpose.

The default implementation of Object class equals() method :

public boolean equals(Object object) {
    return (this == object);
}

Example for .equals() method :

class Student
 {
    String name;
    int rollno;

    Student(String name,int rollno){
      this.name=name;
      this.rollno=rollno;
    }
    
    public static void main(String[] args) {

      Student s1=new Student("Amit",101);
      Student s2=new Student("Naresh",102);
      Student s3=new Student("Amit",101);
      Student s4=s1;

      System.out.println(s1.equals(s2));
      System.out.println(s1.equals(s3));
      System.out.println(s1.equals(s4));
    }
}

Output : False 
         False
         True

Diagram :

In the above program Object class .equals() method got executed which is always
meant for reference comparison that is if two references pointing to the same
object then only .equals() method returns true.
In object class .equals() method is implemented as follows which is meant for
reference comparison.

public boolean equals(Object object) {
    return (this == object);
}
			   

Based on our programming requirement we can override .equals() method for
content comparison purpose.

1 Comment on “Understanding the equals() Method in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *

*