Overriding equals method in Java

equals method in Java

The equals method in Java is a method of class Object. Used to compare two object or two String literals in Java.It returns boolean true or false. When we need to compare two objects we need to Overriding 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 above code String is 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

 

 

 

Add a Comment

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

fourteen − 13 =