• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

StringBuffer

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic