aspose file tools*
The moose likes Beginning Java and the fly likes please explain the output, comparing with String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "please explain the output, comparing with String" Watch "please explain the output, comparing with String" New topic
Author

please explain the output, comparing with String

kumar Nagesh
Greenhorn

Joined: Jan 02, 2007
Posts: 12

StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = new StringBuffer("Hello");
if(sb1.equals(sb2)){
System.out.println("String Buffer False");
}
if (sb1 == sb2) {
System.out.println("False");
}
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9305
    
  17

Just go through the documentation of StringBuffer class. You will find that it doens't override the equals method. So the equals method of Object class is called which uses == for comparing the objects.

Now two StringBuffer objects don't refer to the same object even if they contain the same value. Each StringBuffer object created through the new syntax will always point to a different object. So using == on them will return false...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11417
    
  16

It would help greatly if you would also put in your post what the output IS, and what you EXPECTED it to be. That let's other focus in on what your misunderstanding is, rather than guess on what your confusion is.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: please explain the output, comparing with String