How to visualize recursion

Viewed 7189

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

Stack

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.

3 Answers
Related