Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer

 
Sharda Vajjhala
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9063
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sayed Ibrahim Hashimi
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic