• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
 
Jayakumar Mundanat
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic