-1

I am trying to get the palindrome of a string and below is my code. The problem is, it is only executing the else condition

public class Palindrome {

    public static void main(String[] args) {

        String name = "aba";

        StringBuilder sb = new StringBuilder();

        sb.append(name);

        sb = sb.reverse();
        System.out.println(sb);
        System.out.println(name);
        if (sb.equals(name)) {
            System.out.println(name + " is palindrome");
        } else 
           System.out.println(name + " isn't palindrome");
     }
}

Only the else condition is executed.

GameDroids
  • 5,584
  • 6
  • 40
  • 59

2 Answers2

0

You need to use sb.toString()

if(sb.toString().equals(name)) ...
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

The problem is you are trying to compare instance of a StringBuilder with a String. Those are two separate classes. You should first convert the builder to a string, then compare.

public static void main(String[] args)
    {
        String name = "aba";

        StringBuilder sb = new StringBuilder();

        sb.append(name);
        sb = sb.reverse();
        System.out.println(sb);
        System.out.println(name);
        if (sb.toString().equals(name))
        {
            System.out.println(name + " is palindrome");
        } else System.out.println(name + " isn't palindrome");
    }