Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

StringBuffer equals() query

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys,

public class TestClass
{
public static void main(String Args[])
{
StringBuffer sb1 = new StringBuffer("String");
StringBuffer sb2 = new StringBuffer("String");
if(sb1.equals(sb2))
{
//lots of code
}
}
}

The question is : will the code reach //lots of code ?
Suprisingly the correct answer is : No.

Can anybody please explain ?
 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is "No" because equals() method is not overridden by StringBuffer.
So, the equals() of class Object is invoked which checks for the objects' references equality. Since "new" is used, the references will be different.
 
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would just like to add 1 line to what Vinayagar said,

StringBuffer equals() uses == for comparison. Here sb1 and sb2 refer to 2 different objects, so you get a false.

Gitesh
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic