• 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:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

StringBuffer and String with equal method

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
Can somebody explain me why the output of following code is "false"?

String str ="ram";
StringBuffer sb = new StringBuffer(str);

System.out.println(str.equals(sb));
System.out.println(sb.equals(str));

Thanks in Advance !
 
Bartender
Posts: 4109
72
Hibernate Fedora Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thuogh the value they contain same,they are two different types of objects (one is String and the other is StringBuffer).

Actually equals method of String checks for the object to be a type of String as well,whereas StringBuffer inherits the equals from Object which simply returns true if and only if both objects refers to the same object. So both conditions are false in this case.
[ December 17, 2008: Message edited by: Vijitha Kumara ]
 
Jay Vaghela
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Vijitha
Its clear now...!
 
Marshal
Posts: 74050
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You do of course know how to tell from the API how the equals method works in a particular class?
Try
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic