0
public class Employee {

    String name;

public Employee(String var){ this.name=var;}

} 

public class Main {

    public static void main(String[] args){

        String s1=new String("joe");
        String s2=new String("joe");

        Employee e1=new Employee("joe");
        Employee e2=new Employee("joe");

        system.out.println("When comparing String obj:"+s1.equals(s2));  output:TRUE

        system.out.println("When comparing Employee obj:+e1.equals(e2)): output:FALSE

I know we have to override Employee class but Why it is working for String class and I couldn't able to locate the equals override method in Oracle docs for String class also.Please need help !!

  • 2
    https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object) ? – zerkms Aug 04 '16 at 05:02
  • When you declaring separate object then it will not match condition and it will return false, if you will declare second object as Employee e2 = e1; then it will return true – Vickyexpert Aug 04 '16 at 05:15

4 Answers4

0

In first case you are checking string.

In second case you are checking object of employee.

because two object have different memory address.

more details

Yogesh Rathi
  • 6,331
  • 4
  • 51
  • 81
0

String.equals() returns true if the two strings are not null and contain the same sequence of characters, as specified in the documentation by Oracle. This is different from Object.equals() : Object.equals() returns true if two references point to the same object in memory, see https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

candidus
  • 119
  • 6
0

The reason the example works as it does is because String overrides the equals method to check the content of the String, whereas the Employee class uses the Object.equals method, which checks memory location.

Maybe_Factor
  • 370
  • 3
  • 10
0

Different classes have different criteria for what makes 2 objects "equal". Normally, equals() returns true if it is the same Object:

Object a = new Object();
Object b = new Object();
return(a.equals(b));

This will return false, eventhough they are both "Object" classes, they are not the same instance. a.equals(a) will return true.

However, in cases like a String, you can have 2 different instances but String equality is based on the literal characters that make up those Strings:

String a = new String("example");
String b = new String("example");
String c = new String("another");
a.equals(b);
a.equals(c);

These are all different instances of String, but the first equals will return true because they are both "example", but the 2nd will not because "example" isn't "another".

Nargis
  • 4,687
  • 1
  • 28
  • 45