In the below code It prints "NotSame" Can any one tell me the reason thanks in advance...
public class student {
String name;
student(String name) {
this.name = name;
}
}
public class TestApp{
public static void main(String[] args) {
student s1=new student("A");
student s2=new student("A");
if(s1==s2){
System.out.println("Same");
}else{
System.out.println("NotSame");
}
}
}
This line:
if (s1 == s2)
compares the values of the variables s1
and s2
. Those values are just references. In other words, it's asking whether the values of s1
and s2
refer to the same object. They clearly don't, in this case.
To ask for value equality, you'd usually call equals
:
if (s1.equals(s2))
However, this will still return false
, as you haven't overridden the equals
method in the Student
class. Java assumes object identity for equality unless you tell it otherwise by overriding equals
(and hashCode
).
So you could change your code to:
// Not name change to follow Java conventions. The class is now final
// as well for simplicity; equality for non-final classes can be tricky.
public final class Student {
// Equality tests should usually only use final variables. It's odd
// for two objects to be equal and then non-equal.
private final String name;
Student(String name) {
// TODO: Validate that name isn't null
this.name = name;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Student)) {
return false;
}
Student otherStudent = (Student) other;
return name.equals(otherStudent.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
}
...
Student s1 = new student("A");
Student s2 = new student("A");
if (s1.equals(s2)) {
// Yay!
}
See more on this question at Stackoverflow