Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Equals method in Ojbect class.

807589Nov 4 2008 — edited Nov 4 2008
Hai All,

I am having some doubt regrading equals() method . i have read somewhere in the java book that we are using equals() method for comparing two object content.

like

String string1=new String("selvakumar");
String string2=new String("selvakumar");

if(string1.equals(string2)) {
System.out.println("both the objects are equals");
}

output is : both objects are equals ; this block is working as equals() method purpose.


but when pass my own class objects in to this equals() method ,it is not returning true even though the object having same content .

Equalstesting e1 = new Equalstesting(10);
Equalstesting e2 = new Equalstesting(10);

if(e1.equals(e2))
{
System.out.println("both objects are equals");
}
else
{
System.out.println("both objects are not equals");
}

output is : both objects are not equals.

why ,please explain me the reason? also ,how can i compare this objects ?


My Second Questing : Why we need to override the equals() method in our class . what kind of benefit we will over default one when we override the equals() method.


Thanks

Selvakumar
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 2 2008
Added on Nov 4 2008
17 comments
273 views