Difference between == and .equals() method in Java

The main difference between equals() method and “==” operator is, it is used to compare objects to check equality but with some of the differences.

Difference between equals() and “==”

  1. equals() is a method whereas “==” is an operator.
  2. “==” operator when used for objects it is used to check if both objects point to the same memory location, whereas .equals() method compares the values in that object

Program demonstrating equals() & ==

public class Person
{
  private String fullName;
  // Getters and Setters
}

When we execute below mentioned code then

Person p1 = new Person("John");
Person p2 = new Person("Paul");

System.out.println(p1 == p2);
System.out.println(p1.equaks(p2));


Output:

false
false

Explanation:

  1. p1 == p2 will return false because p1 is referring to one object and p2 is referring to another object, since “==” will check for objects memory hence it will return false.
  2. p1.equals(p2) will return false because the default implementation of .equals() method in object class is to check for objects memory i.e “==” hence it will also return false.

Overriding .equals() method

public class Person
{
  private String fullName;
  
  // Getters and Setters

  @Override
  public boolean equals(Object that){
    if(this == that) return true;//if both of them points the same address in memory

    if(!(that instanceof Person)) return false; // if "that" is not a Person or a childclass

    Person thatPerson = (Person)that; // than we can cast it to Person safely

    // if they have the same name and same age, then the 2 objects are equal unless they're pointing to different memory adresses
    return this.name.equals(thatPerson.getFullName());
  }
}

 


About the course

Learn Selenium with Java by automating Live Project

 

 

Naveen P.N

12+ years of experience in IT with vast experience in executing complex projects using Java, Micro Services , Big Data and Cloud Platforms. I found NPN Training Pvt Ltd a India based startup to provide high quality training for IT professionals. I have trained more than 3000+ IT professionals and helped them to succeed in their career in different technologies. I am very passionate about Technology and Training. I have spent 12 years at Siemens, Yahoo, Amazon and Cisco, developing and managing technology.