What's the difference between ".equals" and "=="? [duplicate]
Solution 1:
In Java, ==
always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals
method can be overridden - so two distinct objects can still be equal.
For example:
String x = "hello";
String y = new String(new char[] { 'h', 'e', 'l', 'l', 'o' });
System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
Additionally, it's worth being aware that any two equal string constants (primarily string literals, but also combinations of string constants via concatenation) will end up referring to the same string. For example:
String x = "hello";
String y = "he" + "llo";
System.out.println(x == y); // true!
Here x
and y
are references to the same string, because y
is a compile-time constant equal to "hello"
.
Solution 2:
The == operator compares if the objects are the same instance. The equals() oerator compares the state of the objects (e.g. if all attributes are equal). You can even override the equals() method to define yourself when an object is equal to another.
Solution 3:
If you and I each walk into the bank, each open a brand new account, and each deposit $100, then...
-
myAccount.equals(yourAccount)
istrue
because they have the same value, but -
myAccount == yourAccount
isfalse
because they are not the same account.
(Assuming appropriate definitions of the Account
class, of course. ;-)