aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Using equals() 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 "Using equals()" Watch "Using equals()" New topic
Author

Using equals()

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
StringBuffer sb1 = new StringBuffer("Test");
StringBuffer sb2= new StringBuffer("Test");
If (sb1.equals(sb2)) -- returns false.
I am unable to understand why it returns false. I thought that sb1 and sb2 are objects so it would return "true".
Can anyone explain me where I am wrong and also about (sb1 == sb2).
Thanks
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20582
    ∞

I went and looked at the source for StringBuffer. It doesn't implement the equals() method. So you only have the default method in Object which does nothing more than see if the two references are the same (which happens to be the same thing that == does).

permaculture Wood Burning Stoves 2.0 - 4-DVD set
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
Strange isn't it. The work around is fairly simple, though: compare sb1.toString() with sb2.toString(). For a little demo see below.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
konda Raju
Greenhorn

Joined: Jan 20, 2000
Posts: 16
bec the equals method is not implemented in
StringBuffer class so it giving false
convert both into string class and try
with the help of equals method it gives true
Ganesh Narayanan
Greenhorn

Joined: Jan 29, 2001
Posts: 7
Frank Carver
That was beautifully explained
Thanx a lot
Wishes
Ganesh
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Using equals()