Just to practice recursion, I wrote one of the classic intro recursive functions - one that checks if a given string is a palindrome.
My question is: within the first if statement, why do I have to write return palChecker(...)
as opposed to just palChecker(...)
? It seems to me the function should work without that first return statement. But from testing I know that's not true, but I'm not really clear on why.
(Btw, the print statements are just there so I could see what was going on during testing. I like actually seeing each executed line.)
public static boolean palChecker(String s){
if ( s.charAt(0)==s.charAt(s.length()-1) && s.length()>1){
System.out.println(s);
return palChecker(s.substring(1,s.length()-1)); //why do i need the return here?
}
else if (s.length()==1 || s.length()==0){
System.out.println(s);
return true;
}
return false;
}