I am trying to understand recursion in Java by visualizing it. I have gone through some tutorials on youtube and using the below example from one of them
public class TestRecursion {
public static void main(String []args) {
new TestRecursion().reduceByOne(10);
}
public void reduceByOne(int n) {
System.out.println("Before "+n);
if(n >= 0) {
reduceByOne(n-1);
System.out.println("Inside "+n);
}
System.out.println("After "+n);
}
}
From what I have understood so far, every call to reduceByOne() would be placed in the execution stack. Something like
So, first main() gets on the stack. Since it calls reduceByOne(10), this method will get onto the stack which would then call reduceByOne(9) and push that to stack and so on. After reduceByOne(-1) is pushed onto the stack, since there are no more methods to execute, reduceByOne(-1) would be popped and executed.
I am having trouble understanding what happens once the method is popped? Lets, says, reduceByOne(2) is popped from the stack. I believe, the code that would be executed would look something like this
public void reduceByOne(2) {
System.out.println("Before "+2);
if(2 >= 0) {
reduceByOne(2-1);
System.out.println("Inside "+2);
}
System.out.println("After "+2);
}
Wouldn't this put reduceByOne(2-1) again onto the stack? Or would it be skipped? If so, how does the runtime know what to execute and what to skip once the method is popped?
May be I am complicating it too much. However, I am not able to get a clear understanding of recursion so any help is much appreciated.
To trace this recursive call in a debugger, set break point on the if statement, and run your program. When the breakpoint is reached: Inspect the value of n , Look at the call stack window.
Recursion is one of the most important ideas in computer science, but it's usually viewed as one of the harder parts of programming to grasp. Books often introduce it much later than iterative control structures.
When the method returns (in your case that will first occur when n >= 0
), the execution will be returned to the previous "call" point, in this case, the next line to be executed would be System.out.println("Inside "+n);
, after which each method would then be proceeded to exit and returned to the previous "call" point in the code
For example...
Green been the "push" and the orange been the result of the "pop"
Obviously, at some point, you'll return to main
, but this is just an illustration
This is not different than how a "normal" code works, you call a method, when it returns, it returns to the point that it was executed previously
This is an oversimplification of the process, but I hope it allows you to better visualize the process
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