Search code examples
javarecursionpalindrome

What is wrong with this Palindrome function


I wrote palindrome function in Java using Recursion but its printing the results incorrectly.

public static boolean isPalindrome(String test) {
        if(test.length() == 1 || test.equals("")) {
            System.out.println("Length is one");
            return true;

        } 

        if (test.charAt(0) == test.charAt(test.length() - 1)) {
            System.out.println("Length is one 111 a");
            isPalindrome(test.substring(1,test.length() -1)) ;      
        } 
        System.out.println("Length is one 111");
        return false;
    }

    public static void main(String args[]) {
        if(isPalindrome("rotor"))
            System.out.println(" Rotor is a palindrome");
        else
            System.out.println(" Rotor is not a palindrome");
        //System.out.println(isPalindrome("rotor"));
        //System.out.println(isPalindrome("motor"));
        //System.out.println(isPalindrome("a"));

    }

Output:

Length is one 111 a
Length is one 111 a
Length is one
Length is one 111
Length is one 111
 Rotor is not a palindrome

Solution

  • You are missing the return statement inside the if. Without it, anything but a string of one or zero characters will ultimately return false:

    public static boolean isPalindrome(String test) {
        if(test.length() <= 1) { // A more elegant check
            return true;
        } 
    
        if (test.charAt(0) == test.charAt(test.length() - 1)) {
            // "return" was missing here
            return isPalindrome(test.substring(1, test.length() -1)) ;      
        } 
        return false;
    }