0

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");
        }
    }
}
olive_tree
  • 1,417
  • 16
  • 23
Faseem
  • 25
  • 1
  • 8
  • 1
    You have to override `.equals()` and `.hashCode()` to tell the language how to compare the objects. – Alnitak Aug 11 '14 at 13:43

3 Answers3

6

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!
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

s1 and s2 point to two different Objects having same value and == compares references not the content within the Objects.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

The reason is that the both are different objects and they are not ==. You'll get "Same" when both instances pointing to same Object.

A real world example might help you to understand:

Take a ball having color red and say that is a redball1.

Take another ball having color red and say that is a red ball2.

Still both are different balls. :)

And take a ball having color red and say that redball. Later you define that "A ball having color red is a redball"(which is implementing equals method of an Object in your class).

Proper way to implement equals and it's effects of wrong implementation.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307