Learn Java · lesson 50 of 61 · about 8 minutes
Methods That Call Themselves
Solve a problem by solving a smaller copy of the same problem.
What you'll learn
- Write a base case that stops the recursion
- Write a recursive case that moves towards it
- Return values from recursive calls
Locking up
The duties are done and the desk is locking up for the night. The manager types how many minutes until the doors lock, and the desk prints Doors lock in 3..., Doors lock in 2..., Doors lock in 1..., then Doors locked. More than 10 minutes is too long to wait. A loop could count, but this unit is about another way: a method that calls itself. lockCountdown(3) prints its line and calls lockCountdown(2), and lockCountdown(0) locks the doors.
A method inside itself
A recursive method calls itself. Each call works on a smaller piece of the problem, until the piece is so small the answer is obvious.
Every recursive method needs two parts:
- A base case that returns without calling itself
- A recursive case that calls itself on something smaller
Counting down
public class Main {
static void countdown(int n) {
if (n == 0) {
System.out.println("Lift off!");
return;
}
System.out.println(n);
countdown(n - 1);
}
public static void main(String[] args) {
countdown(3);
}
}Output
3
2
1
Lift off!Returning an answer
The factorial of 5 is 5 × 4 × 3 × 2 × 1, which is the same as 5 × (the factorial of 4). So factorial(n) can return n * factorial(n - 1), with factorial(1) returning 1.
Factorial
public class Main {
static long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(5));
System.out.println(factorial(15));
}
}Output
120
1307674368000A base case that catches the bottom
The countdown uses if (minutes <= 0) rather than if (minutes == 0). Counting down from 3 lands on 0 either way, but a manager who types 0 or a negative number would never land exactly on 0 with ==, and the calls would go on until Java gave up. <= 0 catches every number at the bottom, so the doors always lock.
Tip
Each call must get closer to the base case. If it never gets there, Java stops the program with a StackOverflowError.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.