File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Using equals()

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).
paul wheaton

Joined: Dec 14, 1998
Posts: 20973

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

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 ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
konda Raju

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

Joined: Jan 29, 2001
Posts: 7
Frank Carver
That was beautifully explained
Thanx a lot
I agree. Here's the link:
subject: Using equals()
It's not a secret anymore!