Hello javaranch team.
i want to clear my about == and equals()
as far as i knows that == basically compares the two object references
and equals() method checks whether the two object references refers to the same object or not
now i m giving the some sample code but i m not understanding it as per the definition of == and equals()
please remove my confusion
when i execute the above program the output is False however the two object references i.e obj1 and obj3 refers to the same object
but if i append the statement as obj1=obj3 then the if statement is true
please explain the above statement that why it is happening
You must override equals() to get meaningful comparisons; by default, the one inherited from Object compares references, just like == does. Note that you should also override hashCode along with equals, and if you implement Comparable, you should make sure that if equals() returns true, compareTo returns 0 - there are only a few special cases when this rule must be broken.
Firstly, your Obj1 and Obj3 are not refering to the same object. Whenever you do a new it will create a seperate object in memory.
I tried you code with both equals and == but it gave false both time. This is what is expected.
For Object class, since the equals and Hashcode methods are not overriden, it checks for object reference. For Object both equals and == mean same.
Now, the reason why people would ask you to override equals and hashcode is to define you own way of distinguishing between two objects. As a simple example, if you have 2 Objects of Dog class, you need to define why these two Dogs are different. What rule Java should use to distinguish between them.
For String class, the equals and Hashcode are overriden.
Try below code and see the difference(I have used object of class String):
public static void main(String ar)
Object obj1=new String("Hello");
Object obj2=new String("Hi");
Object obj3=new String("Hello");