• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Using equals()

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Trailboss
Posts: 23778
IntelliJ IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
Sheriff
Posts: 7001
6
Eclipse IDE Python C++ Debian Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Frank Carver
That was beautifully explained
Thanx a lot
Wishes
Ganesh
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic