• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer and equals

 
Fes D Gaur
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code


StringBuffer sb1 = new StringBuffer("abcd");
StringBuffer sb2 = new StringBuffer("abcd");
System.out.println(sb1.equals(sb2));

The above code compiles. Does the StringBuffer class override equals() ? If not then why doesn't the compiler give and error at sb1.equals(sb2) ??

Thanks,

Fes
 
Abdulla Mamuwala
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Fes

The StringBuffer class does not override equals() it uses the one from the Object class. Refer API. The Object equals() method checks for the equality of the references. In your code sb1 and sb2 have different references, therefore the code should compile fine, but return a false, even though the Strings are identical. You can try the following piece of code to check if the references contain identical Strings,
.
The output will be true.
 
srikanth reddy
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes abdulla,










the first two prints false

whereas third and fourth print true and false respectively

so we can say that StringBuffer has not overridden equals method.


thanks

sri
 
Fes D Gaur
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the response guys. I know now that the inherited methods should also be looked at. But one thing I don't understand, why does the statement

System.out.println(sb1.equals.sb2);

return false. Doesn't equals check if the two objects are meaningfully equal instead of comparing their reference like "==" does?

Thanks,
Fes
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here,

equals(..) checks for the references

This is what is defined for the method in the Object class...

unless you override the method ... like in string class..

where it is overridden to compare the contents of the object...

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic