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
Eclipse can generate equals and hashCode for you.
Vineet Kakati wrote:Refer the following link to get difference between'==' and equals();
Be careful with that article! It might confuse people, as it does not explain why the following is true
You will get TRUE for both the tests.
For an explanation, see my post at http://www.coderanch.com/t/487350/Performance/java/Best-way-compare-strings (it's one of the last posts there).
I think a good source of info is the javadoc for java.lang.Object - check equals() and hashCode, as well as the developerWorks article.
No, that is only the un-overridden Object#equals() method. You override it to accept other types of equality. Google for Angelika Langer Java equals or find the chapter in Joshua Bloch's Effective Java, for more details. It looks easy at first sight, but it is actually very difficult.
sharma sachin wrote: . . . equals() method checks whether the two object references refers to the same object or not . . .
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");
//if(obj1 == obj3)