1

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

bragboy
35.7k30 gold badges116 silver badges175 bronze badges
asked Jun 22, 2010 at 8:38

3 Answers 3

3

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());
answered Jun 22, 2010 at 8:41

4 Comments

Then how do I compare as like String objects?
Follow-up, for JavaUser: StringBuffer documentation -- 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](java.sun.com/javase/6/docs/api/java/lang/… )
@JavaUser You can look up the documentation for String this way as well -- note what String#equals says about itself.
@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.
2

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

answered Jun 22, 2010 at 8:44

Comments

0
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())
answered Jun 22, 2010 at 8:47

1 Comment

@unbeli : It should have been addresses. Thanks.. corrected the answer

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.