Do we have to override .equals in our own classes? [duplicate]

I have some code here that creates 2 Student objects and then checks if they are equal or not:

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

public class Main{

    public static void main(String args[]){  
            Student s1=new Student(101,"Vance");  
            Student s2=new Student(101,"Vance"); 
              
            System.out.println(s1.num+" "+s1.name);  
            System.out.println(s2.num+" "+s2.name);  
            if(s1==s2){
                System.out.println("They are the same object");
            }
            if(s1.equals(s2)){
                System.out.println("They have the same values ");
            }      
    }  
}  

And both of those if statements do not print out anything, when I thought the second one would. I know that == checks if 2 variables reference the same object, which is false here, but doesn't .equals check if the content of 2 objects are equivalent? Why is it returning false here if it's a Student object with the same exact content? Do we have to override it and write our own?



Read more here: https://stackoverflow.com/questions/67390707/do-we-have-to-override-equals-in-our-own-classes

Content Attribution

This content was originally published by Vance at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: