jQuery in Action, 2nd edition*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "a doubt in equals() method" Watch "a doubt in equals() method" New topic
Author

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.

question:

class a
{
a(int x)
{
System.out.println(x);
}
}

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

System.out.println(ob1.equals(ob2));
}
}


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,
regards,
raja
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
Greenhorn

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 ]
 
 
subject: a doubt in equals() method