How is recursion implemented in Java? My question is about what happens behind when a recusrsive method is executed in Java. I vaguely understand that it uses the Stack, but i am looking for a clear explanation with example.
How is recursion implemented in Java? My question is about what happens behind when
Share
Recursion isn’t handled much differently in Java than in other (imperative) languages.
There’s a stack which holds a stack frame for every method invocation. That stack is the call stack (or simply just “stack”, when the context makes it clear what is meant). The element on the stack are called “stack frames”.
A stack frame holds the method arguments passed in and the local variables of a method invocation (and possibly some other data, such as the return address).
When a method invokes itself (or, in fact, any method) then a new stack frame is created for the parameters and local variables of the newly-called method.
During the method execution the code can only access the values in the current (i.e. top-most) stack frame.
This way a single (local) variable can seemingly have many different values at the same time.
Recursion isn’t handled any other way than normal method calls, except that multiple stack frames will represent invocations of the same method at the same time.