File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StringBuffer equals() method 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 equals() method" Watch "StringBuffer equals() method" New topic

StringBuffer equals() method

md ali

Joined: Sep 06, 2001
Posts: 25
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2= new StringBuffer("hello");
Why this code prints false. Is there some difference in StringBuffer equals() method.
Muhammad Ali
Abdul Latif
Ranch Hand

Joined: Jul 18, 2001
Posts: 89
There is no equals method defined for the StringBuffer class
& so it uses the equals method inherited from the Object class
& the Object class equals method does not work properly as intended. For your code to return true u have to subclass SringBuffer & provide equals method for it.
hope this helps
md ali

Joined: Sep 06, 2001
Posts: 25
It is strange thing. Are there also some other classes from Sun which do not have a well defined equals method. And can somebody tell that what is the reason for not having an equals() method well defined in StringBuffer or any other class.
Muhammad Ali
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi md,
The default 'equals()' returns 'true' if both references point to the same object in memory. That's an easy 'value' to determine.
'equality' has to do with comparing values; one person's idea of 'equality' may be different from anothers.
Overriding equals() for String and the wrapper classes (Boolean, Double, Integer, etc) was an easy call for the developers as the classes are immutable and it's not difficult to arrive at a consensus as to what qualifies as a useful 'value'.
For mutable objects it might be tougher. Are StringBuffers equal only if they are the same size and have the same characters? or only if they have the same characters, regardless of the buffer size? or only if they have the same set of contiguous characters? or only if ... you see the problem
Hope that helps.
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform

Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
I agree. Here's the link:
subject: StringBuffer equals() method
Similar Threads
Equal method
equals method and StringBuffer
please explain the output, comparing with String