I'm working on some introductory recursion problems and I have a clarifying question I'd like to get answered. The most nagging question I have is how is this recursion operating in the solved problem below?
Despite having solved the problem, I'm just not understanding how the recursion call makes its way into the interior of the string. It would seem, from just looking at the code, that this method would only ever check the two characters on either end of the given string, without checking the rest. My textbook gives the deeply unsatisfying answer of, basically, don't worry about how recursion works as long as your return statement refines the problem. But I'm having difficulty knowing how to approach subsequent recursion problems without understanding how one can trace a recursive method in the same way one would trace a loop.
Any words of wisdom would be much appreciated.
Thanks!
public class isPalindrome {
public static boolean isPalindrome(String str)
{
//test for end of recursion
if(str.length() < 2) {return true;}
//check first and last character for equality
if(str.charAt(0) != str.charAt(str.length() - 1)){return false;}
//recursion call
return isPalindrome(str.substring(1, str.length() - 1));
}
public static void main(String[] args)
{
System.out.print(isPalindrome("deed"));
}
}