[Solved] How recursive function works internally


If I interpreted your question correctly, you’re not really confused about the recursion part, you’re more confused about how the value num gets assigned to num – 1 part. The answer to this is that num is never being reassigned in the first place, at least not in its own lexical scope.

What that basically means is that there is a different value of “num” in each function call of m1() on the call stack (they will be, in this case, 4, 3, 2, 1, and 0 before the recursion terminates). The variable num is not reassigned in the function call because “num – 1” itself is just an expression, not an assignment. The value of num on each function call on the call stack is actually a different “num” variable all together, and this has to do with the fact that java is “pass by value”.

In general, if you’re looking to brush up your understanding of recursion, highly suggest checking out the book “The Little Schemer”.

solved How recursive function works internally