How to visualize recursion

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...

Stack And Pop

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


I will explain what happens when the recursion occurs using your example. As you know the method which is on top of the stack gets executed and get popped out. This explanation is just for understanding purpose.

You have confused with the idea when method/method state is pushed and popped from the stack.

public static void main(String []args) {
    new TestRecursion().reduceByOne(10); //first line
}

Main method get on top of the stack.

Stack -> main()

Now as the first line encounters it calls reduceByOne(10). So that gets added to the stack.

Stack -> reduceByOne(10) main()

As reduceByOne(10) is on top of the stack,execution of main() pauses, and execution of reduceByOne(10) starts. As the execution of line

reduceByOne(n-1);

Another method call occurs and its pushed to stack. So current method pauses execution because reduceByOne(9) is now on top of stack.

Stack -> reduceByOne(9) reduceByOne(10) main()

Similarly stacks gets added with method states.

Stack -> reduceByOne(-1) --- reduceByOne(9) reduceByOne(10) main()

When reduceByOne(-1); is executed, if condition in the method fails.

if(n >= 0) { // now n is -1
    reduceByOne(n-1);
    System.out.println("Inside "+n);
}

And it completes the execution, reduceByOne(-1) gets popped out. Now reduceByOne(0) resumes execution from the line

...
System.out.println("Inside "+n); // ---- line(1)
    }
    System.out.println("After "+n);
}

and gets popped out. Now reduceByOne(1) resumes execution from line(1) as gets popped out. Now reduceByOne(2) is on top of the stack, it resumes its execution from line(1). Similarly it comes back upto reduceByOne(10). And now reduceByOne(10) completes execution resuming from line(1) and gets popped out. Now only main method remains in the stack. It also gets executed and popped out. Thus execution terminates.

Tags:

Java

Recursion