==
between two objects, such as strings, compares whether they are the same instance. .equals()
, on the other hand, compares them to see if they have the same value.
Consider the possibility that you have a class called Point. Points are made up of two ints, x and y and are allowed to move. I have two points, A, at (0, 0), and B, at (1, 0). Right now, neither ==
nor .equals()
would return true. A moment later, B moves to be at (0, 0). ==
is still false, because I still have two instances of points and they aren't the same, but .equals()
is now true because they have the same value of (0, 0).
Similarly, you should use .equals()
if you want to check if two strings have the same value (you almost always want that,) or ==
if you want to check if two strings are the exact same string.
==
behaves differently when comparing primitive numbers, like straight up ints. ==
is a check to see if they have the same value and there's no equivalent concept of checking for their identity - if you'd like to have ints that have identities, consider using the Integer class instead of the int primitive.