Chapter 8. Recursive Methods
Up to this point, we’ve been using while
and for
loops whenever we’ve needed to repeat something. Methods that use iteration are called iterative. They are straight-forward, but sometimes more-elegant solutions exist.
In this chapter, we explore one of the most magical things that a method can do: invoke itself to solve a smaller version of the same problem. A method that invokes itself is called recursive.
Recursive Void Methods
Consider the following example:
public
static
void
countdown
(
int
n
)
{
if
(
n
==
0
)
{
System
.
out
.
println
(
"Blastoff!"
);
}
else
{
System
.
out
.
println
(
n
);
countdown
(
n
-
1
);
}
}
The name of the method is countdown
; it takes a single integer as a parameter. If the parameter is 0, it displays the word Blastoff. Otherwise, it displays the number and then invokes itself, passing n - 1
as the argument.
What happens if we invoke countdown(3)
from main
?
The execution of
countdown
begins withn == 3
, and sincen
is not 0, it displays the value 3, and then invokes itself...The execution of
countdown
begins withn == 2
, and sincen
is not 0, it displays the value 2, and then invokes itself...The execution of
countdown
begins withn == 1
, and sincen
is not zero, it displays the value 1, and then invokes itself...The execution of
countdown
begins withn == 0
, and sincen
is 0, it displays the word Blastoff! and then returns.The
countdown
that gotn == 1
returns.The
countdown
that gotn == 2
returns.The
countdown
that gotn == 3
returns. ...
Get Think Java, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.