What is the difference between == and equals() in Java?
I wanted to clarify if I understand this correctly:
-
==
is a reference comparison, i.e. both objects point to the same memory location -
.equals()
evaluates to the comparison of values in the objects
In general, the answer to your question is "yes", but...
-
.equals(...)
will only compare what it is written to compare, no more, no less. - If a class does not override the equals method, then it defaults to the
equals(Object o)
method of the closest parent class that has overridden this method. - If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you're left with the
Object#equals(Object o)
method. Per the Object API this is the same as==
; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality. - Always remember to override
hashCode
if you overrideequals
so as not to "break the contract". As per the API, the result returned from thehashCode()
method for two objects must be the same if theirequals
methods show that they are equivalent. The converse is not necessarily true.
With respect to the String class:
The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn't make a difference. Its the "value" (that is: the contents of the character array) inside each String instance that is being compared.
On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".
As with any explanation, let it sink in.
I hope this clears things up a bit.