wood burning stoves 2.0*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "StringBuffer" Watch "StringBuffer" New topic
Author

StringBuffer

Sharda Vajjhala
Ranch Hand

Joined: Nov 14, 2001
Posts: 57
Hi!
I have the following code:
class StrBuf{
public static void main(String args[]){
String s1 = "abcde";
StringBuffer s2 = new StringBuffer("abcde");
if(s1.equals(s2))
System.out.println("s1 equals s2!");
if(s2.equals(s1))
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?
Thanks
Sharda
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
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.


JavaBeginnersFaq
"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="http://www.cise.ufl.edu/~sih" target="_blank" rel="nofollow">www.cise.ufl.edu/~sih</a>
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: StringBuffer
 
Similar Threads
String and equals
StringBuffer
question on "immutable" strings
equals or not?
StringBuffer