Search code examples
javacachingequalsreferenceequals

Overriding .equals() method (== returned true while comparing Strings)!


public class Employee {

private String firstName;
private String lastName;
private int age;

public Employee(String firstName, String lastName, int age) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}

public boolean equals(Employee s) {
    if (this.firstName==s.firstName  && this.lastName == s.lastName) { //Line 1
        return true;
    }
    return false;
}

public static void main(String agrs[]) {

    Employee e1 = new Employee("Jon", "Smith", 30);
    Employee e2 = new Employee("Jon", "Smith", 35);

    System.out.println(e1.equals(e2));
}

}

Line 1 returned true while comparing two Strings with == operator.I thought "Jon" and "Smith" of e1 and e2 will be having two different references(memory location).

What concept is taking care of "Jon" and "Smith" of e1 and e2 to have same references?(String caching??! or Is it just coincidental?)


Solution

  • This is because of string interning. The string literals "Jon" and "Smith" are compiled into the same string and saved in the string constant pool by the compiler. Hence in this case, both constructors would reference the same instance.

    You can see the difference using the below:

    Employee e1 = new Employee("Jon", "Smith", 30);
    Employee e2 = new Employee("Jon", "Smith", 35);
    Employee e3 = new Employee(new String("Jon"), new String("Smith"), 35);
    
    System.out.println(e1.equals(e2));  // true
    System.out.println(e1.equals(e3));  // false