Java Reference
In-Depth Information
For simplicity, suppose that we invoke this method with the statement
countDown(3);
from within a main method of the class that defines countDown . This call behaves like any other call
to a nonrecursive method. The argument 3 is copied into the parameter integer and the following
statements are executed:
System.out.println(3);
if (3 > 1)
countDown(3 - 1); // first recursive call
A line containing 3 is displayed, and the recursive call countDown(2) occurs, as Figure 7-2a shows.
Execution of the method is suspended until the results of countDown(2) are known. In this
particular method definition, no statements appear after the recursive call. So although it
appears that nothing will happen when execution resumes, it is here that the method returns to
the client.
FIGURE 7-2
The effect of the method call countDown(3)
(a)
(b)
(c)
countDown(3)
countDown(2)
countDown(1)
Display 3
Call countDown(2)
Display 2
Call countDown(1)
Display 1
7.9
Continuing our trace, countDown(2) causes the following statements to execute:
System.out.println(2);
if (2 > 1)
countDown(2 - 1); // second recursive call
A line containing 2 is displayed, and the recursive call countDown(1) occurs, as shown in
Figure 7-2b. Execution of the method is suspended until the results of countDown(1) are known.
The call countDown(1) causes the following statements to execute:
System.out.println(1);
if (1 > 1)
A line containing 1 is displayed, as Figure 7-2c shows, and no other recursive call occurs.
Figure 7-3 illustrates the sequence of events from the time that countDown is first called. The
numbered arrows indicate the order of the recursive calls and the returns from the method. After 1
is displayed, the method completes execution and returns to the point (arrow 4) after the call
countDown(2 - 1) . Execution continues from there and the method returns to the point (arrow 5)
after the call countDown(3 - 1) . Ultimately, a return to the point (arrow 6) after the initial recursive
call in main occurs.
Search WWH ::




Custom Search