File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

StringBuffer

Anonymous
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";
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

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.
This
Anonymous
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
Thanks
Jayakumar Mundanat
Greenhorn

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.
 
 
subject: StringBuffer
 
Similar Threads
string buffer
Doubt in StirngBuffer
String Q
equals method and StringBuffer
please explain the output, comparing with String