Java Reference
In-Depth Information
FIGURE 7-4
The stack of activation records during the execution of the call
countDown(3)
(d)
(a)
(b)
(c)
main(. . .):
main(. . .):
main(. . .):
main(. . .):
countDown(3):
countDown(3):
countDown(3):
countDown(2):
countDown(2):
integer: 3
R
eturn to calling point
in
main
countDown(1):
integer: 2
R
eturn to calling point
in
countDown
integer: 1
R
eturn to calling point
in
countDown
(e)
(g)
(f)
main(. . .):
main(. . .):
main(. . .):
countDown(3):
countDown(3):
countDown(2):
integer: 3
R
eturn to calling point
in
main
integer: 2
R
eturn to calling point
in
countDown
Note:
The stack of activation records
Each call to a method generates an activation record that captures the state of the method's execution
and that is placed into the program stack. Figure 5-13 in Chapter 5 illustrated the program stack
when
methodA
calls the distinct method
methodB
. However, these methods need not be distinct.
That is, the program stack enables a run-time environment to execute recursive methods. Each invo-
cation of any method produces an activation record that is pushed onto the program stack. The acti-
vation record of a recursive method is not special in any way.
Note:
A recursive method uses more memory than an iterative method, in general, because
each recursive call generates an activation record.
Programming Tip:
Stack overflow
A recursive method that makes many recursive calls will place many activation records in the
program stack. Too many recursive calls can use all the memory available for the program
stack, making it full. As a result, the error message “stack overflow” occurs. Infinite recur-
sion or large-size problems are the likely causes of this error.