What is the difference between a == b
and a.Equals(b)
?
Suppose we have a
and b
or two different objects and we want to compare these two object references. Then we use the ==
operator and when using a.equals(b)
, it compares the string values.
==
uses the reference of an object, or if an integer/float etc, then it compares the actual number. Technically it just compares what in the memory location.
Whereas .equals
uses a method inside the object class to compare objects, it can be overridden for your individual classes.
Also as arrays also deal with references, its also helpful not to use array1[i] = array2[i]
, use arraycopy
or clone()
.
I think .equals
can also be used with arrays
== checks if references are pointing to the same object in the memory
Now,
although the code of equals method in object class is nothing but checking == for the references, it can be overridden to add your own equality checks.
In classes like String, the overridden method checks if the string literals are correct or not. So basically it can be used to check if value is same or not.
==
checks the Object reference, basically it compares the hashcodes. Equals uses the contents in the object. Remember, we have to override the .equals
method accordingly in our class.
a == b
returns true if the references contain the same value, i.e., they point to the same object, or they are both null.
The equals()
method can be overridden to compare objects. For example, on Strings
, the method returns true
if the strings contain the same string, even if they are different string objects. You can do similar things with your own objects.
o.equals()
will throw an exception if o is a null reference.