Java Reference
In-Depth Information
PITFALL: Infinite Recursion
In the example of the method
writeVertical
discussed in the previous subsections,
the series of recursive calls eventually reached a call of the method that did not
involve recursion (that is, a stopping case was reached). If, on the other hand, every
recursive call produces another recursive call, then a call to the method will, in theory,
run forever. This is called
infinite recursion
. In practice, such a method will typically
run until the computer runs out of resources and the program terminates abnormally.
Examples of infi nite recursion are not hard to come by. The following is a syntacti-
cally correct Java method defi nition, which might result from an attempt to defi ne an
alternative version of the method
writeVertical
:
public static void
newWriteVertical(
int
n)
{
newWriteVertical(n / 10);
System.out.println(n % 10);
}
If you embed this definition in a program that calls this method, the program
will compile with no error messages and you can run the program. Moreover,
the definition even has a certain reasonableness to it. It says that to output the
argument to
newWriteVertical
, first output all but the last digit and then output
the last digit. However, when called, this method will produce an infinite sequence
of recursive calls. If you call
newWriteVertical(12)
, that execution will stop
to execute the recursive call
newWriteVertical(12/10)
, which is equivalent to
newWriteVertical(1)
. The execution of that recursive call will, in turn, stop to
execute the recursive call
newWriteVertical(1 / 10);
which is equivalent to
newWriteVertical(0);
This, in turn, will stop to execute the recursive call
newWriteVertical(0 / 10);
which
is also equivalent to
newWriteVertical(0);
This will produce another recursive call to again execute the same recursive
method call
newWriteVertical(0);
and so on, forever. Because the definition of
newWriteVertical
has no stopping case, the process will proceed forever (or until
the computer runs out of resources).
■