I am learning recursion and below is one example that I am tracing through to better understand it
public static void main(String []args) {
new TestRecursion().strRecur("abc");
}
public void strRecur(String s) {
if(s.length() < 6) {
System.out.println(s);
strRecur(s+"*");
}
}
Below is what I have understood so far.
- In the first call to strRecur("abc"), the method gets added to execution stack. It prints "abc" before pausing due to a recursive call with parameter "abc*".
The second call with "abc*", pushes method
strRecur(abc*)to the stack and prints "abc*" to console.The third call with "abc**", pushes method
strRecur(abc**)to the stack and prints "abc**" to console.The fourth call with "abc***", pushes method
strRecur(abc***)to the stack. Since the base condition is met, the method completes (without printing anything) and pops out of the stack.The third call with "abc**" is completed and popped out. Since there is no pending code to execute nothing happens.
The second call with "abc*" is completed and popped out. Since there is no pending code to execute nothing happens.
The initial call with "abc" is completed and popped out. Since there is no pending code to execute nothing happens.
Prints following to the console -
abc
abc*
abc**
I think I understand what is happening here. Now, I want to try a slight variation of this code. Instead of callingstrRecur(s+"*"), I would like to do return strRecur(s+"*")
public class TestRecursion {
public static void main(String []args) {
new TestRecursion().strRecur("abc");
}
public String strRecur(String s) {
if(s.length() < 6) {
System.out.println(s);
return strRecur(s+"*");
}
return "Outside If";
}
}
My expectation was that, once strRecur(abc***) pops out, it's output (abc***) would be returned to the next strRecur() on the stack, so I would see abc**** printed in the console. Same for other recursive calls as well.
However, the output in this case is exactly the same as when there is no return statement. My understanding (which of course is not correct) stems from the recursive factorial implementation, where we do something like
return n * fact(n-1);
Here fact(n-1) is resolved with the returned value of n, once the previous method on the stack completes. Why doesn't return behave in the same way in this example?

System.err.println( "> strRecur s="+s);and before returning, you doSystem.err.println("< strRecur s="+s);. Then you can trace what is being called with what input parameter and in what order. Maybe not with this relatively simple recursion, but when you get to learn about more complicated scenarios, this may help a lot.