posted 17 years ago
If you use '==' to compare two non-primitive values, you only get true if the values refer to the exact same object - so, for example, you have two variables that refer to the same object:
Most of the time, this is not what you want when you are comparing objects. You usually want to see if two objects represent the same values, even if they are really different objects. You use the equals() method to compare two objects to see if they have the same value.
Note that for the equals() method to work properly, you need to override it, because the equals() method in class Object does the same as '=='.
If you look in the API documentation, you will see that class StringBuffer does not have an overridden equals() method. That means that if you call equals() on a StringBuffer, it will use the implementation in class Object, which just does '=='.
Class String does have an overridden equals() method, but you can only use it to compare the String to another String object. If you pass in any other kind of object (a StringBuffer, for example) it will always return false.
So you cannot compare String and StringBuffer objects to each other directly. If you want to see if the contents of a StringBuffer is equal to the contents of a String, then you have to call toString() on the StringBuffer and compare the two strings:
Your example will print 'false' three times because:
1. sb1 and sb2 refer to different StringBuffer objects, so == returns false
2. StringBuffer has no equals() method, so the equals() method in Object is used, which uses ==, so you get false again
3. The same reason as point 2
[ August 30, 2007: Message edited by: Jesper Young ]