1

Looking to gain a better understanding of .equals vs == in java

In particular I was curious how these behave at the memory level?

Everything I've read so far states that == looks to see if the objects refer to the same memory location while .equals will compare the content of the objects within a given memory location.

What is the advantage to comparing content versus the actual memory location? Is there any instances where .equals would behave different from == or vice a versa?

mtcrts70
  • 35
  • 4
  • 19

1 Answers1

0

Yes, there can be very, very important differences. Two different objects created with the same values will not be equal by reference, but you still often want to see if they represent the same logical value. For example:

Point a = new Point(0, 0);
Point b = new Point(0, 0);
System.out.println(a == b);      // prints 'false'
System.out.println(a.equals(b)); // prints 'true'
Alexis King
  • 43,109
  • 15
  • 131
  • 205