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
Am I correct in my understanding ?
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 objectsAm I correct in my understanding ?
Also note that
.equals()
normally contains==
for testing as this is the first thing you would wish to test for if you wanted to test if two objects are equal.And
==
actually does look at values for primitive types, for objects it checks the reference.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.
The String pool (aka interning) and Integer pool blur the difference further, and may allow you to use
==
for objects in some cases instead of.equals
This can give you greater performance (?), at the cost of greater complexity.
E.g.:
Complexity tradeoff: the following may surprise you:
I advise you to stay away from such micro-optimization, and always use
.equals
for objects, and==
for primitives:----Output----- true false true