Search code examples
javarecursionpalindrome

Recursive method in java to detect a palindrome


I´m trying to trace the recursive method that detect if a word is a palindrome or not:

public static boolean isPalindrome(String word) {
    if (word.length() == 0 || word.length() == 1) {
        return true; 
    } else if (word.charAt(0) == word.charAt(word.length() - 1)) {
        return isPalindrome(word.substring(1, word.length() - 1)); 
    } else {
        return false;
    } 
}

The word that I've used is: "abba". The first instance of the method takes the else way because the evaluation of the first if condition, so it evaluates the condition in the if else statement obtaining a true as result, then the method returns the running of the method with the word "bb". The recursion runs the method again: the length of "bb" is not 0 or 1, then it takes the else way, and evaluates if the first 'b' is equals to the second 'b', is true, so returns the running of the same method again, but now with a substring that starts in the character in position 1 (beginIndex) 'b' and ends in the character in position 0 (endIndex), but beginIndex is greater than the endIndex and this should Throws IndexOutOfBoundsException ... However the method works. Can somebody explain this to me? Thanks


Solution

  • In your second iteration the word is bb. Which means the length is 2.

    And your substring is, word.substring(1, 1). Hence it wont (and correctly so) thrown an exception, instead return an empty string.