• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

StringBuffer

 
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Why in StringBuffer class in both the cases it returns false
StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2= new StringBuffer("Amit");
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
Regards,
aakash
 
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In case of �==�object reference are compared. Hence it returns false since sb1 and sb2 are in two different location.
Since equals method is not overridden in StringBuffer class. Default implementation from Object class is present in StringBuffer. The default implemation is again check for object reference, not the object value. Hence since sb1 and sb2 are referring different
memory location in the second case also it is returns false.
 
aakash bhatt
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Arun,
How should I compare 2 StringBuffer values for equality
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Convert them to Strings and then do an .equals
if (sb1.toString().equals(sb2.toString()))
 
Arun Boraiah
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
just an extension to Thomas suggestion. Make sure that sb1 and sb2 is never null.
 
Let's get him boys! We'll make him read this tiny ad!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic