File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "StringBuffer" Watch "StringBuffer" New topic
Author

StringBuffer

aakash bhatt
Ranch Hand

Joined: Jan 09, 2003
Posts: 182
Hi all,
Why in StringBuffer class in both the cases it returns false
StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2= new StringBuffer("Amit");
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
Regards,
aakash
Arun Boraiah
Ranch Hand

Joined: Nov 28, 2001
Posts: 233
In case of �==�object reference are compared. Hence it returns false since sb1 and sb2 are in two different location.
Since equals method is not overridden in StringBuffer class. Default implementation from Object class is present in StringBuffer. The default implemation is again check for object reference, not the object value. Hence since sb1 and sb2 are referring different
memory location in the second case also it is returns false.


Sharing is learning
aakash bhatt
Ranch Hand

Joined: Jan 09, 2003
Posts: 182
Hi Arun,
How should I compare 2 StringBuffer values for equality
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Convert them to Strings and then do an .equals
if (sb1.toString().equals(sb2.toString()))


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Arun Boraiah
Ranch Hand

Joined: Nov 28, 2001
Posts: 233
just an extension to Thomas suggestion. Make sure that sb1 and sb2 is never null.
 
 
subject: StringBuffer