How does method call in stack gets executed – Recursion

I have a question on recursion. Whenever a base condition is hit in recursion we stop making recursive calls and then method calls in stack keeps executing and gets popped out of the memory stack one by one.

My question is once we hit that base condition and now there is no more recursive calls, so when we execute the first method call in the stack, how does the process know like it doesn’t have to call the method again and has to execute it and popped it out of the stack memory ?

For e.g., Let’s take a look at this piece code

private static String reverse(String str) {
    if(str.equals("")) {
        return "";
    return reverse(str.substring(1)) + str.charAt(0);

Input : my name is slim shady

Output : ydahs mils si eman ym

When we do string reversal, now the base condition is if string is empty then no need of calling the same method, but once we hit that base condition there are method calls on stack reverse("o") + "l". Like in this image

enter image description here

How does the process know that it has to execute that method and pop out rather than making another recursive call ? Because this method reverse("o") + "l" looks like another call instead of executing it and popping it out of memory.


Don’t think of the stack as having pieces of code on it, but a program counter which will resume executing at a particular point in the method.

We can split reverse(str.substring(1)) + str.charAt(0) up like this (which is roughly what it will look like after it has been compiled):

tmp = reverse(str.substring(1));
tmp = tmp + str.charAt(0);
return tmp;

When the call to reverse() is made, the program counter pushed onto the stack will point at tmp = tmp + str.charAt(0);, so that’s where execution will resume when the recursive call returns.