1

I am checking if a String "nitin" is a palindrome but it's returning false.

Please anyone help me to shorout this.

public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("nitin");
    sb.reverse();
    String rev = sb.toString();

    System.out.println(sb);
    System.out.println(rev);

    if (sb.equals(rev)) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
}
Akp
  • 259
  • 1
  • 9
  • 2
    https://stackoverflow.com/questions/2012305/comparing-stringbuffer-content-with-equals (it's a different question, but the answer also applies here) – NPE Apr 14 '18 at 06:57

3 Answers3

4

You are comparing the StringBuffer with the String. Try with if (sb.toString().equals(rev)) {

Rashin
  • 726
  • 6
  • 16
1

sb is a StringBuffer, rev is a String. These two objects of different types cannot be compared for "String value equality" with each other.

Use if (sb.toString().equals(rev)): this way you compare if two strings are equal, as sb.toString() is converted to a String.

Also, it is wrong at the beginning to reverse sb. That is because at the time you declare String rev = sb.toString(), sb is already reversed. Unreverse sb by calling sb.reverse() again after declaring rev. Your final code should be

    StringBuffer sb = new StringBuffer("nitdin");
    sb.reverse(); // reversed sb
    String rev = sb.toString(); // rev is reversed sb to String
    sb.reverse(); // unreversed sb

    ...

    if (sb.toString().equals(rev)) // String-string comparison
  • String rev=sb.toString(); check this line – Akp Apr 14 '18 at 07:00
  • 2
    "*They cannot be compared.*" - They can. And the fact that they can is the cause of OPs problem. It is just always `false`. – Turing85 Apr 14 '18 at 07:14
  • @Mulliganaceous Why is it "not useful"? When is a comparision "useful"? I would tend to choose a neutral wording. – Turing85 Apr 14 '18 at 07:19
0

You might misunderstand the StringBuffer and String. Your code might need to change

    StringBuffer sb=new StringBuffer("nitin");
    String before = sb.toString();
    sb.reverse();
    String after = sb.toString();
    System.out.println(before);
    System.out.println(after);
    System.out.println(before == after);
    if(before.equals(after)){
        System.out.println("true");
    }else{
        System.out.println("false");
    }
Bejond
  • 1,188
  • 1
  • 11
  • 18