Java Reference
In-Depth Information
output the
digit 2
When this suspended computation resumes, it executes an output statement that
outputs the value 12 % 10 , which is 2 . That ends that computation, but there is
yet another suspended computation waiting to resume. When this last suspended
computation resumes, the situation is
if (123 < 10)
{
System.out.println(123);
}
else //n is two or more digits long:
{
writeVertical(123 / 10);
System.out.println(123 % 10);
}
Computation resumes
here.
When this last suspended computation resumes, it outputs the value 123 % 10 , which is 3 ,
and the execution of the original method call ends. And, sure enough, the digits 1 , 2 , and 3
have been written to the screen one per line, in that order.
output the
digit 3
A Closer Look at Recursion
The definition of the method writeVertical uses recursion. Yet, we did nothing
new or different in evaluating the method call writeVertical(123) . We treated it
just like any of the method calls we saw in previous chapters. We simply substituted
the argument 123 for the parameter n and then executed the code in the body of the
method definition. When we reached the recursive call
writeVertical(123 / 10)
we simply repeated this process one more time.
The computer keeps track of recursive calls in the following way. When a method
is called, the computer plugs in the arguments for the parameter(s) and begins to
execute the code. If it should encounter a recursive call, then it temporarily stops
its computation, because it must know the result of the recursive call before it can
proceed. It saves all the information it needs to continue the computation later on,
and proceeds to evaluate the recursive call. When the recursive call is completed, the
computer returns to finish the outer computation.
The Java language places no restrictions on how recursive calls are used in method
definitions. However, in order for a recursive method definition to be useful, it must
be designed so that any call of the method must ultimately terminate with some piece
of code that does not depend on recursion. The method may call itself, and that
recursive call may call the method again. The process may be repeated any number of
how
recursion
works
how
recursion
ends
 
Search WWH ::




Custom Search