Java Reference
In-Depth Information
FIGURE 7-3
Tracing the recursive call countDown(3)
// Client
public static void main(...)
{
countDown(3);
...
} // end main
1
public static void countDown(3)
{
System.out.println(3); . . . . . . . . . . . . . . . . . . . . 3 is displayed
if (3 > 1)
countDown(3 - 1);
} // end countDown
6
2
public static void countDown(2)
{
System.out.println(2); . . . . . . . . . . . . . . . . . . . . 2 is displayed
if (2 > 1)
countDown(2 - 1);
} // end countDown
5
3
public static void countDown(1)
{
System.out.println(1); . . . . . . . . . . . . . . . . . . . . 1 is displayed
if (1 > 1)
} // end countDown
4
Although tracking these method returns seems like a formality that has gained us nothing, it is
an important part of any trace because some recursive methods will do more than simply return to
their calling method. You will see an example of such a method shortly.
7.10
Figure 7-3 appears to show multiple copies of the method countDown . In reality, however, multiple
copies do not exist. Instead, for each call to a method—be it recursive or not—Java records the cur-
rent state of the method's execution, including the values of its parameters and local variables as
well as the location of the current instruction. As Segment 5.22 of Chapter 5 described, each record
is called an activation record and provides a snapshot of a method's state during its execution. The
records are placed into the program stack. The stack organizes the records chronologically, so that
the record of the currently executing method is on top. In this way, Java can suspend the execution
of a recursive method and invoke it again with new argument values. The boxes in Figure 7-3 cor-
respond roughly to activation records, although the figure does not show them in the order in which
they would appear in a stack. Figure 7-4 illustrates the stack of activation records as a result of the
call countDown(3) in a main method.
Search WWH ::




Custom Search