aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How to Compare StringBuffer object with String Object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How to Compare StringBuffer object with String Object" Watch "How to Compare StringBuffer object with String Object" New topic
Author

How to Compare StringBuffer object with String Object

jerry sharma
Greenhorn

Joined: Mar 30, 2006
Posts: 23
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

Joined: Nov 16, 2005
Posts: 502

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());


Prabhu Venkatachalam<br />SCJP 1.4,SCWCD 1.4<br />prabhu.venkatachalam@gmail.com
jerry sharma
Greenhorn

Joined: Mar 30, 2006
Posts: 23
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

Joined: Nov 16, 2005
Posts: 502

have you tried this?

Sanjeev Singh
Ranch Hand

Joined: Nov 01, 2006
Posts: 381
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.


~Sanjeev Singh<br />SCJP 1.5
venkatesh pendharkar
Ranch Hand

Joined: Apr 29, 2006
Posts: 106
why dont you use contentEquals() method from String class.
boolean contentEquals(StringBuffer sb)
Krzysztof Koziol
Ranch Hand

Joined: Nov 19, 2006
Posts: 133

To compare only its content (not objects) could we do like this:

System.out.println(s.compareTo(sb.toString())==0?true:false);


SCJP 5.0, SCWCD 5.0, SCBCD 5.0, SCEA/OCMJEA 5.0
 
Don't get me started about those stupid light bulbs.
 
subject: How to Compare StringBuffer object with String Object