The operator ==
check if two objects are the same.
You created two different equals object.
So they are not the same and s1 == s2
will return false.
You have to redefine the method equals
and check them with this method as follow:
s1.equals(s2)
The method equals
:
Indicates whether some other object is "equal to" this one.
Note that when you redefine the method equals you need also to redefine the method hashCode, as explicitly documentated in the description of equals method:
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
Generally ide (like IntelliJ, Eclipse or Netbeans) helps you writing a good implementation of both methods.
Considering this I suppose that the interviewer has asked something like How will s1 equals s2 talking about it and you misunderstood it as How will s1 (simble equals) s2. Or he has explicitly written the operator ==
on the paper?
If the interviewer asked explicitly how to will
s1 == s2 // returns true
after creating the two objects as
Student s1 = new Student();
Student s2 = new Student();
The only possibility is to change the reference of s1 (or s2) as follow:
Student s1 = new Student();
Student s2 = new Student();
s1 = s2; // new added line , or the same if you write s2 == s1
s1 == s2 // now is true
But this is a trick, infact you are testing that two different variables are referencing the same object.
You can have a similar behaviour assigning to both variables null
, or another Student
previously created. Basically any change to code that assign to s1
the same reference of s2
will work.