Java Reference
In-Depth Information
18.6 Recursion and the Method-Call Stack
In Chapter 6, the stack data structure was introduced in the context of understanding how
Java performs method calls. We discussed both the method-call stack and stack frames . In
this section, we'll use these concepts to demonstrate how the program-execution stack
handles recursive method calls.
Let's begin by returning to the Fibonacci example—specifically, calling method fibo-
nacci with the value 3 , as in Fig. 18.6. To show the order in which the method calls' stack
frames are placed on the stack, we've lettered the method calls in Fig. 18.7.
A
fibonacci( 3 )
B
fibonacci( 2 )
E
fibonacci( 1 )
C
fibonacci( 1 )
D
fibonacci( 0 )
return 1
return 1
return 0
Fig. 18.7 | Method calls made within the call fibonacci(3) .
When the first method call ( A ) is made, a stack frame containing the value of the local
variable number ( 3 , in this case) is pushed onto the program-execution stack . This stack,
including the stack frame for method call A , is illustrated in part (a) of Fig. 18.8. [ Note:
We use a simplified stack here. An actual program-execution stack and its stack frames
would be more complex than in Fig. 18.8, containing such information as where the
method call is to return to when it has completed execution.]
(a)
(b)
(c)
(d)
Top of Stack
Top of Stack
Top of Stack
Method call: C
number = 1
Method call: B
number = 2
Method call: A
number = 3
Method call: D
number = 0
Method call: B
number = 2
Method call: A
number = 3
Top of Stack
Method call: E
number = 1
Method call: A
number = 3
Method call: A
number = 3
Fig. 18.8 | Method calls on the program-execution stack.
 
 
Search WWH ::




Custom Search