jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StringBuffer" Watch "StringBuffer" New topic


Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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";
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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
Jayakumar Mundanat

Joined: Jun 17, 2000
Posts: 11
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.
I agree. Here's the link: http://aspose.com/file-tools
subject: StringBuffer
It's not a secret anymore!