Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive method: why do I need return statement?

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;
}
like image 318
yellowFreet Avatar asked Mar 19 '23 13:03

yellowFreet


2 Answers

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.

like image 155
ErstwhileIII Avatar answered Apr 02 '23 14:04

ErstwhileIII


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.

  1. palChecker("ABCBA") executes palChecker("BCB")
  2. palChecker("BCB") executes palChecker("C")
  3. palChecker("C") executes return true
  4. 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
  5. 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
  6. final result is 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;
    }
}
like image 20
Apprentice Queue Avatar answered Apr 02 '23 14:04

Apprentice Queue