When you compare two object references using == operator, it evaluate to true only when both references refer to same object. public class Person { private Integer id; private String name; public Person(Integer id, String name) { this.id = id; this.name = name; } public static void main(String[] args) { Person p1 = new Person(1, "Prithvi"); Person p2 = p1; Person p3= new Person(1, "Prithvi"); System.out.println(p1==p2); System.out.println(p1==p3); } } Output: true false We have created 3 references of Person class. Object references p1 and p2 both refer to same object so comparison evaluate to true. Comparison of p1 and p3 evaluate to false, even though p3 has same contents as p1 but refer to different object so comparison returns false. Below image explains this - Objects p3 and p1 are meaningfully equal. We must have some way to see their content are same or not. But the question is, How will you compare two different object
Good set of questions...
ReplyDelete