File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes a doubt in equals() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "a doubt in equals() method" Watch "a doubt in equals() method" New topic

a doubt in equals() method

rajaraman navaneethan
Ranch Hand

Joined: Feb 26, 2005
Posts: 86
hello friends,
thanx very much for your previous responses for my doubt in exception hadling.plz clear me of this doubt about equals() method.


class a
a(int x)

class b
public static void main(String args[])
a ob1=new a(100);
a ob2=new a(100);


the output of this is false,even though both ob1 and ob2 are objects of class a and the value passed to the constructor is also same.i thought that .equals() method checks the contents of the object and returns a boolean value.
please clear me of this doubt as how .equal() works,
Horatio Westock
Ranch Hand

Joined: Feb 23, 2005
Posts: 221
The default equals method (supplied by java.lang.Object) actually uses ==

If you want to use equals for your own classes, you have to override public boolean equals(Object o), and make it do something sensible for your type.

this might be interesting
Subbarao Anaparthi

Joined: Mar 01, 2005
Posts: 2
equals() on Object(Except for String & Wrapper Classes) uses == operator.

for example
Object o=new Object();
Object o1=o;
if(o1.equals(o)) returns true becaus o,o1 references points to same object.
equals() is overridden into String & Wrapper Classes.
and equals() in String and All Wrapper classes compares the contents in the reference variable.

thats why equals() works differently on String & StringBuffer.
because equals() on StringBuffer takes equals() from Object and equals() on String takes the overridden method in String class.

[ March 01, 2005: Message edited by: Subbarao Anaparthi ]
[ March 01, 2005: Message edited by: Subbarao Anaparthi ]
I agree. Here's the link:
subject: a doubt in equals() method
It's not a secret anymore!