Quote:
Originally Posted by HelloWorld That part is the most confusing to me, since it returns, doesn't that meant hat it should be getting out from the method itself? How can it pick up from where it left off?  |
I'd like to elaborate on something I mentioned in my previous post
Quote:
|
Originally Posted by Bench Recursion causes multiple different calls of the same function to be placed on a stack frame. |
In other words, recursion causes multiple instances of a method-call to be created. In this context, it would be sensible to think of a method-call as an object with a presence in memory.. or at least, on the stack frame, which will be active in memory somewhere, recording the state of individual method-calls.
You can think of a Method/function as a
Named block of code. Its almost like meta-programming, where a single-line method-call is replaced by the contents of that entire method.
for example, here's a program with some nested method calls. Exactly the same thing happens with the stack frame as the recursive calls before, just with different methods.
PHP Code:
public static void DoSomething()
{
System.out.println("DoSomething is added on-top of the stack frame");
}
public static void SomeMethod()
{
System.out.println("SomeMethod is added on-top of the stack frame");
DoSomething();
System.out.println("SomeMethod at the top again");
}
public static void main(String args[])
{
System.out.println("main is at the top of the stack frame");
SomeMethod();
System.out.println("main is at the top of the stack frame again");
}
If you un-rolled the stack frame in-to main, the program would look like this
PHP Code:
public static void main(String args[])
{
System.out.println("main is at the top of the stack frame");
//Begin SomeMethod()
System.out.println("SomeMethod is added on-top of the stack frame");
//Begin DoSomething()
System.out.println("DoSomething is added on-top of the stack frame");
//End DoSomething()
System.out.println("SomeMethod at the top again");
//End SomeMethod()
System.out.println("main is at the top of the stack frame again");
at the point when DoSomething() is called, the stack frame looks like this
Code:
-top-
DoSomething()
SomeMethod()
main()
-bottom-
If you run the program, you should be able to see that when DoSomething() ends, the function returns to the point in SomeMethod() where DoSomething() was called from. Because SomeMethod is temporarily 'frozen', with its state recorded on the stack frame - therefore, it picks up where it left off when it becomes active again