views:

46

answers:

3

Why String.equls() returns true but Stringbuilder.equals() returns false?

    StringBuffer sb1 = new StringBuffer("Amit");
    StringBuffer sb2= new StringBuffer("Amit");
    String ss1 = "Amit";
    String ss2 = "Amit";

System.out.println(sb1.equals(sb2)); //returns false
System.out.println(ss1.equals(ss2)); //returns true

Thx

+2  A: 

StringBuffer does not override Object's equals() method, and thus, it returns true only when a StringBuffer object is compared with itself.

public boolean equals(Object obj) {
    return (this == obj);
}

To compare two StringBuffers based on their contents, do something like this:

sb1.toString().equals(sb2.toString());
Lauri Lehtinen
Then how do I compare as like String objects?
JavaUser
Follow-up, for JavaUser: [StringBuffer documentation](http://java.sun.com/javase/6/docs/api/java/lang/StringBuffer.html) -- as you can see the 'equals' method is not overridden in StringBuffer (at the bottom of method list there is "Methods inherited from class java.lang.Object", which contains "equals"), thus you can observe the behavior of StringBuffer#equals is that of [Object#equals](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object) )
pst
@JavaUser You can look up the documentation for String this way as well -- note what [String#equals](http://java.sun.com/javase/6/docs/api/java/lang/String.html#equals(java.lang.Object)) says about itself.
pst
So String class overrides equals() method ..Am I right?
JavaUser
@JavaUser yes, String first checks if the object it's being compared to is itself, if not, it check if the other object is also a String and finally if all the characters match.
Lauri Lehtinen
@JavaUser yes, it does.
unbeli
+2  A: 

StringBuffer does not define equals method, so Object's equals method is used, which only returns true if it's the same object. You can do

sb1.toString().equals(sb2.toString())

if you want to compare them as Strings

unbeli
A: 
StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2= new StringBuffer("Amit");
String ss1 = "Amit";
String ss2 = "Amit";

System.out.println(sb1.equals(sb2)); //returns false
System.out.println(ss1.equals(ss2)); //returns true

In the first case sb1.equals(sb2), sb1 and sb2 will have two different addresses because it does not override the equals() method. If you really want to do a comparison that returns you true is

sb1.toString().equals(sb2.toString())
Bragboy
hashcode is irrelevant here.
unbeli
@unbeli : It should have been addresses. Thanks.. corrected the answer
Bragboy