Reputation: 6029
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.
Upvotes: 0
Views: 2165
Reputation: 39628
when a method if invoked it needs space to keep its parameters, its local variables and the return adress this space is called activation record (stack frame).
Recursion is calling a method that happens to have the same name as the caller, therefore a recursive call is not litterally a method calling it self but an instantiation of a method calling another instantiation of the same original. these invocations are represented internally by different activation records which means that they are differentiated by the system.
Upvotes: 0
Reputation: 308051
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.
Upvotes: 11