Difference between equals() Method and == in Java

Published by user on

In this post, we are going to look at the difference between the equals method and == in Java

equals() method can do a deep comparison, whereas == operator does a shallow comparison.

What are the differences?

  • == operator compares the memory location of the objects, whereas the equals() method compares the instance variables within objects.
  • For equals() to return the correct results class has to override it. If the class hasn’t overridden the method, then it uses the Object class equals() method.
  • If the class is inheriting from a parent class and hasn’t overridden the method, then equals() of the nearest parent is called.
  • For == operator no need to override anything.
  • We cannot customize the behavior of ==.
  • For primitive data types only == operator is used.

 

Difference between equals() Method and == in Java

Let’s understand through the example.

Example 1:

public class Comparison {

  public static void main(String[] args) {

    String str1 = new String("Java");
    String str2 = new String("Java");

    // compares value
    System.out.println(str1.equals(str2));

    // compares memory location
    System.out.println(str1 == str2);
  }
}

Output:

true
false

Here we create two String objects using the new keyword, str1, and str2, and both the objects use different memory locations.

The first comparison returns true as the content is the same, i.e., “Java”.
The second comparison returns false as the object memory locations are different.

Example 2:
In this example, we are not creating new objects.

public class Comparison {

  public static void main(String[] args) {

    String str1 = "Java";
    String str2 = "Java";

    System.out.println(str1.equals(str2));

    System.out.println(str1 == str2);

  }
}

Output:

true
true

Here we directly assign values to String, so both objects are using the same memory location. As the memory location and values are the same, both the comparisons return true.

Comparing Objects with equals() Method

// Java class that
// represents Person
public class Person {

  private String name;

  private int age;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Person other = (Person) obj;
    if (age != other.age)
      return false;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    return true;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + age;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
  }
}
// Java class to test custom equals
// method
public class CustomComparison {

  public static void main(String[] args) {

    Person p1 = new Person();
    p1.setName("Person1");
    p1.setAge(20);

    Person p2 = new Person();
    p2.setName("Person1");
    p2.setAge(20);

    Person p3 = new Person();
    p3.setName("Person2");
    p3.setAge(29);

    System.out.println(p1.equals(p2));
    System.out.println(p2.equals(p3));
  }
}

Output:

true
false

We implemented equals() in Person class and included name and age property.
When we call this method on a Person object, then it compares objects for the same name and same age.
If the name and age in both the objects are the same, then it returns true else it returns false.

Explanation:
In the first comparison, p1 and p2 have the same name and age, so the result is true.
In the second comparison, p1 and p3 have different names and ages; hence, it returns false.

Questions and Answers

Can we compare two incompatible types using ==?
A comparison between two incompatible data types is not possible using == operator.
We get compiler error “Incompatible operand types.”

Can we customize the behavior of == operator?
No. We cannot customize the behavior of == operator.

Summary:

  1. We saw the difference between equals() method and == in java.
  2. equals() does content comparison and == does memory location comparison.
  3. By overriding equals(), we can customize its behavior.
  4. If there is no equals() in the class it calls Object’s equals() method.
  5. == can compare compatible data types.
  6. Incompatible data types comparison using == operator results in compiler error.

If you like this article, please share it.

Categories: Java