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;
}
You need to return the value eventually returned by PalChecker
.
The definition of a Java function is that it always returns a value ... even if it is a chain from the deepest point in your recursion, bringing true or false finally to the top.
If you were missing return palChecker
, then it will never return true
unless s
is length 0 or 1. Because when palChecker recursively discovers the answer is true
, there is no way for it to return that discovery back to you; it will just go to the return false
line when the recursion returns.
palChecker("ABCBA")
executes palChecker("BCB")
palChecker("BCB")
executes palChecker("C")
palChecker("C")
executes return true
palChecker("BCB")
receives that true
but if you are missing the return statement, it does not return it; it moves to the next line of code which is return false
palChecker("ABCBA")
receives that false
but if you are missing the return statement, it moves to the next line of code which is return false
false
It is more clear if you can rewrite with explicit else
.
public static boolean palChecker(String s){
if (s.length()==1 || s.length()==0){
System.out.println(s);
return true;
}
// at this point s.length() > 1
if (s.charAt(0)==s.charAt(s.length()-1)){
System.out.println(s);
return palChecker(s.substring(1,s.length()));
}
else {
// mismatch
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With