The "Emp" class inherits the equals() method from the root "OBJECT" class.
Below is the equals() method code present in Object class :
public boolean equals(Object obj)
{
return (this == obj);
}
As you can see above which checks for the memory location address for equality.
First case :
Emp e1 = new Emp("hello");
Emp e2 = new Emp("hello");
System.out.println(e1 == e2);
Here you are comparing the reference( memory location ), since you have created two new objects in heap, there memroy location are different and hence it retuned "false"
Second case :
Emp e1 = new Emp("hello");
Emp e2 = new Emp("hello");
System.out.println(e1.equals(e2));
Here you are involing the inherited equals() method from the "Object" class which inturn check for the references ( memory location ) of these two objects and hence retuned false.
Third case :
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);
In this case the String class has the equals() method overridden which actually check for the object fields for comparison, below is the source code for equals() method in String class :
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
This is similar to first case, here you are comparing the reference( memory location ) of two string objects, since you have created two new objects in heap, there memroy location are different and hence it retuned "false"
Fourth case :
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2));
Here you are invoking the overridden equals() method from the string class ( the code pasted above ). if you see the logic it first actually checks if the two refrences are referring to same memory location if same it returns true, else it will actually check the contents of the two string objects which is backed by the charcter array, it compares each and every character with the coressponding charcter of these tow string objects, since both the objects have same contents " hello", it returned true.
As Ken mentioned above please go through the equals() and hashcode() contract.