1

I have a class named student contains two variables name,no and i have created two objects for the class, now i want to check whether both objects are same or not. I am using .equals() method but i am not getting proper output.

public class Student {
    String name;
    int no;

    Student(String name,int no){
        this.name=name;
        this.no=no;
    }

    public static void main(String[] args) {
        Student s1 = new Student("abc", 10);
        Student s2 = new Student("abc", 10);
        System.out.println(s1.equals(s2));
    }
}

output: false

Philipp Kief
  • 8,172
  • 5
  • 33
  • 43
Siddu
  • 156
  • 7
  • 2
    You need to override 'equals()' in Student class, by default it is Object class whic compares object references – Ryuzaki L Oct 01 '18 at 06:11
  • You need override equals method with `name` and `no`. – xingbin Oct 01 '18 at 06:11
  • Here the way you can override equals method @Override public boolean equals(Object obj){ if(obj == null){ return false; } final Student student = (Student) obj; if(student.name.equals(this.name) && student.no == this.no){ return true; }else{ return false; } } – Sudhir Ojha Oct 01 '18 at 06:25

1 Answers1

2

You haven't provided an implementation of equals, meaning it will use the default one it inherits from Object, which is the same as: s1 == s2, which returns false because they are not the same object.

You'll need to provide your own implementation.

Take a look at this.

Stultuske
  • 9,296
  • 1
  • 25
  • 37