Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare Stringbuffer object and String object

Tags:

java

how to compare sb and s

StringBuffer sb= new StringBuffer("Hello");
String s= "Hello";

s.equals(sb.toString()) is giving result as false.

like image 466
Ramya Tantry Avatar asked Jun 21 '26 18:06

Ramya Tantry


2 Answers

Unable to reproduce:

public class Test {
    public static void main(String[] args) {
        StringBuffer sb= new StringBuffer("Hello");
        String s= "Hello";
        System.out.println(s.equals(sb.toString())); // Prints true
    }
}

If you think the two values are really the same, please post a similar short but complete program demonstrating the problem. I suspect you'll find the problem is elsewhere - such as some invisible characters in the string or StringBuffer.

like image 188
Jon Skeet Avatar answered Jun 24 '26 07:06

Jon Skeet


It is definitely returning true for me. As the content of both strings (the String object you created and the String object returned by the StringBuffer toString()) are the same, the equals() method shouldn't return false.

like image 41
talnicolas Avatar answered Jun 24 '26 06:06

talnicolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!