File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "StringBuffer" Watch "StringBuffer" New topic


Sharda Vajjhala
Ranch Hand

Joined: Nov 14, 2001
Posts: 57
I have the following code:
class StrBuf{
public static void main(String args[]){
String s1 = "abcde";
StringBuffer s2 = new StringBuffer("abcde");
System.out.println("s1 equals s2!");
System.out.println("s2 equals s1");
This does not print out anything upon execution. I thought it would print out the "s1 equals s2"(from the 1st if stmt).
Can anyone explain the output?
Marilyn de Queiroz

Joined: Jul 22, 2000
Posts: 9058
StringBuffer, unlike String, does not override the Object version of the equals() method. Therefore, for StringBuffer, the statement s1.equals(s2); is equivalent to s1 == s2 ;

Since s1 and s2 are different objects are not at the same address, they are not equal and nothing prints.

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Sayed Ibrahim Hashimi
Ranch Hand

Joined: May 17, 2001
Posts: 148
If you want to see if the contents of a StringBuffer and a String are equal then you should use the String method 'contentEquals(StringBuffer sb)'.
For more info look at the API docs.

SCJP 1.4<br /><a href="" target="_blank" rel="nofollow"></a>
I agree. Here's the link:
subject: StringBuffer
It's not a secret anymore!