• 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

How to Compare StringBuffer object with String Object

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All dear Friends !

Please help me out to understand

StringBuffer sb= new StringBuffer("Hello");
String s= "Hello";
how if we want to know the contents of s & sb are equal.

regards
 
Ranch Hand
Posts: 502
jQuery Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can convert StringBuffer to String by using its overridden toString() method which will return you String object with content initialized.

s.equals(sb.toString());
 
jerry sharma
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think still it will not compare the contents of both the objects and it gives you result as a false.
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
jQuery Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
have you tried this?

 
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
s.equals(sb.toString()) is the only way to check whether the two strings are same or not.
s.equals(sb) will return false always because for the s to be meaningfully equals to sb,sb should be either String or any subclass of String(which is not possible).See the equal()(Object overriden) method in String Class.
 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
why dont you use contentEquals() method from String class.
boolean contentEquals(StringBuffer sb)
 
Ranch Hand
Posts: 133
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To compare only its content (not objects) could we do like this:

System.out.println(s.compareTo(sb.toString())==0?true:false);
reply
    Bookmark Topic Watch Topic
  • New Topic