Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to Compare StringBuffer object with String Object

 
jerry sharma
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • 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
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • 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
  • 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
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
have you tried this?

 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • 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.
 
venkatesh pendharkar
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why dont you use contentEquals() method from String class.
boolean contentEquals(StringBuffer sb)
 
Krzysztof Koziol
Ranch Hand
Posts: 133
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • 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);
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic