• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using equals()

 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 21181
Firefox Browser IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Frank Carver
Sheriff
Posts: 6920
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strange isn't it. The work around is fairly simple, though: compare sb1.toString() with sb2.toString(). For a little demo see below.
 
konda Raju
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Frank Carver
That was beautifully explained
Thanx a lot
Wishes
Ganesh
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic