Win a copy of Head First Android this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

a doubt in equals() method

 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 2
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic