• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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: 4116
72
Mac TypeScript Chrome Java Linux
  • 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: 79177
377
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic