Example to Overriding equals method in Java

Equals method in Java

equals() is a method of Object class. Used to compare two objects or two String literals in Java. It returns boolean true or false. When we need to compare two objects we need to Override the equals() method in Java.

Let’s take an example where we are going to compare two objects without Overriding equals method in Java.

public class OverrideEquals {

  private String s3;

  public OverrideEquals(String string) {
    // TODO Auto-generated constructor stub
    this.s3 = string;
  }

  public static void main(String[] args) {

    OverrideEquals obj = new OverrideEquals("codebun");
    OverrideEquals obj1 = new OverrideEquals("codebun");
    System.out.println(obj.equals(obj1));

  }

}

Output: false

You can see in the above code String is the same, but we are getting output is false.

Now let’s see the same example with overriding equals method in Java.

Overriding equals method in Java

public class OverrideEquals {

  private String s3;

  public OverrideEquals(String string) {
    // TODO Auto-generated constructor stub
    this.s3 = string;
  }


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



  public static void main(String[] args) {

    OverrideEquals obj = new OverrideEquals("codebun");
    OverrideEquals obj1 = new OverrideEquals("codebun");
    System.out.println(obj.equals(obj1));

  }

}

Output: true