GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StringBuffer and equals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StringBuffer and equals" Watch "StringBuffer and equals" New topic
Author

StringBuffer and equals

Fes D Gaur
Ranch Hand

Joined: Apr 29, 2005
Posts: 54
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

Joined: Jan 09, 2004
Posts: 225
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

Joined: Jul 28, 2005
Posts: 252
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


Thanks & Regards<br /> <br />-Srikanth
Fes D Gaur
Ranch Hand

Joined: Apr 29, 2005
Posts: 54
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

Joined: Jul 04, 2004
Posts: 979
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...

 
GeeCON Prague 2014
 
subject: StringBuffer and equals