• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

StringBuffer

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,
Does StringBuffer act the same way as String when using equals method? If not,can anyone explain me the o/p of this program.
class sb1
{
public static void main(String a[])
{
StringBuffer sb1 = new StringBuffer("avn");
StringBuffer sb2 = new StringBuffer("avn");
String ss= "avn";
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss));
}
}
O/P:false.false,false.
thanks
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi avn.U see,StringBuffer class does not override equals method.The equals in StringBuffer just inherits it's behaviour from equals of Object class,which does a == comparison.Thus even if u do a StringBuffer.equals(StringBuffer) test all u will get is false.To really compare StringBuffers for equality,do a
sb1.toString().equals(sb2.toString())test instead.
This
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks! Udayan.I am clear with it.
I do need explanation for the following code o/p also:

//assuming the below code is in a class
String ss1="AMIT";
String ss2="amit";
System.out.println(ss1.compareTo(ss2));--o/p is -32
System.out.println(ss2.compareTo(ss1));--o/p is 32
Thanks
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The compareTo() method (usually associated with the Comparable interface used for Set/Map functions) returns a negative,= or a positive number depending on the comparison lexicographically .Since 'a' has a different ASCII code from 'A' the result will vary depending on which string the compareTo() fn is operated on.
 
He does not suffer fools gladly. But this tiny ad does:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic