Recursion: a method that calls itself
22 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Recursion means a method calls itself. Each call works on a smaller value, until a simple case stops the calls.
A method that calls itself
Counting down from 3 means "say 3, then count down from 2": the job holds a smaller copy of itself. Recursion is a method that calls itself, each time with a smaller value.
Example 1 · Countdown with recursion
public class RecCountdown { public static void main(String[] args) { countdown(3); }
static void countdown(int n) { if (n == 0) { System.out.println("Go!"); return; } System.out.println(n); countdown(n - 1); }}3 2 1 Go!
What this code does
countdown(n - 1)is the recursive call: the method calls itself with one less.if (n == 0)is the base case: it printsGo!and stops, so the calls end. In avoidmethod,return;with no value just ends the method.- The calls go
countdown(3),countdown(2),countdown(1),countdown(0), and the last one stops.
Calls go in, answers come back
factorial(3) is 3 × 2 × 1, but the method cannot multiply until it knows factorial(2). Each call waits with its own n until the smaller call returns, then finishes its own part.
Trace the code
Step through factorial(3)
Variables
None yet.
Output
(nothing printed yet)Line 3main calls factorial(3) and waits for its answer.
n. The last call made is the first to finish.Work before or after the call
Move the println below the recursive call, and the countdown comes out upside down. Lines after the call run on the way back, once the smaller calls have finished.
Example 2 · Print on the way back
public class CountUp { public static void main(String[] args) { countUp(3); }
static void countUp(int n) { if (n == 0) { return; } countUp(n - 1); System.out.println(n); }}1 2 3
What this code does
countUp(3)callscountUp(2)before it prints anything; that callscountUp(1), which callscountUp(0), the base case.- Only on the way back does each call print its
n: first the call with 1, then 2, then 3.
When recursion never stops
Leave out the base case, or never reach it, and the method keeps calling itself. Every waiting call takes stack space, so Java soon stops with java.lang.StackOverflowError.
Find the bug
Spot the recursion bug
Select the line that is wrong.
countdown(3) should print 3, 2, 1 and then Go!
Round 1 of 3Next step
Check your understanding
8 quick questions