0

I am trying to make a Palindrome checker in Java but my when I check the reverse method compared to the input string to see if they are equivalent, I am getting false. Even when I use obvious palindromes like "racecar". My reverse method uses recursion to reverse an input string.

public class Palindrome
{
    public static String reverse( String input )
    {
        if( input.length() == 1 )
            return input;
        return reverse( input.substring( 1 ) ) + input.charAt( 0 ); 
    }

    public static boolean isPalindrome( String input )
    {
        if( Palindrome.reverse( input ) == input )
            return true;
        return false;
    }

    public static void main( String args[] )
    {
        System.out.println( Palindrome.isPalindrome( "racecar" ) );
    }
}

1 Answers1

0

Use .equals() instead of == to fix your code.

Note you could condense your code into something like this:

public static boolean isPalindrome(String str) {
    return str.equals(new StringBuilder(str).reverse().toString());
}
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40