-3

Source Code:

public class TestSB{
    public static void main(String args[]){
        String s1="Arnold";
        StringBuffer sb1=new StringBuffer("Arnold");
        StringBuffer sb2=new StringBuffer("Arnold");
        System.out.println(sb1==sb2);
        System.out.println(sb1.equals(sb2)); //should be true but printing false
       System.out.println(sb1.equals(s1)); //should be true but printing false
    }
}

Above is a Source Code that I have written, the output for line 7 and line 8 both should be true but it is coming false what is the reason behind this?

Output:

false
false
false
  • Please take the [Tour](http://stackoverflow.com/tour) and read the documentation in the [Help Center](http://stackoverflow.com/help). In particular, you should read about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and what sorts of questions are [on topic](http://stackoverflow.com/help/on-topic) here at SO. – azurefrog Jun 27 '19 at 19:43
  • 2
    Please also read: [Why can't I upload images of code on SO when asking a question?](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question) – azurefrog Jun 27 '19 at 19:44
  • If you have problems formatting your code, SO has a [markdown help page](https://stackoverflow.com/editing-help) that can help you out. – azurefrog Jun 27 '19 at 19:45
  • When object of StringBuffer is passed references are compared because StringBuffer does not override equals method of Object class. – Nongthonbam Tonthoi Jun 27 '19 at 19:45
  • Why "should" it be `true`? Are you under the assumption a `StringBuffer` is the same thing as a `String`? Did you check the docs for `StringBuffer` to see what `equals` it implements? And all the other comments: questions need to stand on their own, and links to images of text are worse only than images of text: post text. – Dave Newton Jun 27 '19 at 19:46

1 Answers1

0

That is because StringBuffer / StringBuilder do not override Object#equals, as you might have expected. You should use sb1.toString().equals(sb2.toString()) or sb1.toString().equals(str) to compare SB as as String value.

Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34