Lesson 11 of 34 · Methods
Java Recursion: Methods That Call Themselves
Some problems contain smaller copies of themselves. The factorial of 5 is 5 times the factorial of 4; a folder's size is its files plus the sizes of the folders inside it. Recursion solves such problems with a method that calls itself on a smaller piece of the problem until the piece is trivial.
Base case and recursive case
static int factorial(int n) {
if (n <= 1) {
return 1; // base case: answer known directly
}
return n * factorial(n - 1); // recursive case: a smaller problem
}
Every recursive method needs both parts:
- a base case that returns an answer without recursing, and
- a recursive case that calls the method again on an input that is closer to the base case.
What happens on the call stack
Each call gets its own stack frame with its own copy of n. The calls pile up until the base case is reached, then the results flow back down:
factorial(4)
4 * factorial(3)
3 * factorial(2)
2 * factorial(1)
1 ← base case
2 * 1 = 2
3 * 2 = 6
4 * 6 = 24
Nothing is multiplied until the deepest call returns — each frame waits for the one above it.
Recursion on numbers and Strings
Splitting off one piece at a time works for digits:
static int sumDigits(int n) {
if (n < 10) {
return n; // a single digit
}
return n % 10 + sumDigits(n / 10); // last digit + the rest
}
sumDigits(4096) becomes 6 + sumDigits(409), then 9 + sumDigits(40), and so on, giving 19. The same idea works for text, where the smaller problem is a shorter String:
static String reverse(String s) {
if (s.isEmpty()) {
return "";
}
return reverse(s.substring(1)) + s.charAt(0);
}
When recursion goes wrong
If the base case is missing, or the input never gets smaller, the method keeps calling itself until the call stack runs out of space and Java stops with a StackOverflowError:
static int forever(int n) {
return forever(n + 1); // no base case
}
Exception in thread "main" java.lang.StackOverflowError
Even correct recursion has a limit: a few thousand nested calls are fine, millions are not.
Recursion or a loop?
Any recursive method can be rewritten with a loop, and loops are often faster. The naive recursive Fibonacci, fib(n - 1) + fib(n - 2), recomputes the same values again and again: fib(40) makes hundreds of millions of calls, while a loop needs forty steps. Recursion shines when the problem is naturally nested — trees, mazes, folders inside folders, divide-and-conquer algorithms — because the code mirrors the structure of the data.
Common mistakes
- No base case, or one that can never be reached (for example
if (n == 0)whennstarts negative). - Not shrinking the input:
factorial(n)insidefactorialrecurses forever; it must befactorial(n - 1). - Forgetting
return: callingfactorial(n - 1);without using its result throws the answer away. - Overflowing
int: factorials grow fast.13!no longer fits in anint, so uselong.
Assignment
Write four recursive methods in Main (no loops):
factorial(int n)returnsn!as along(n ≥ 0):factorial(5)is120,factorial(0)is1,factorial(20)is2432902008176640000.power(int base, int exponent)returnsbaseraised toexponentas along(exponent ≥ 0):power(2, 10)is1024,power(5, 0)is1.sumDigits(int n)returns the sum of the digits ofn(n ≥ 0):sumDigits(4096)is19.isPalindrome(String s)returnstrueifsreads the same forwards and backwards:"racecar"is,"java"is not. The empty String and single characters are palindromes.
Premium lesson
Unlock the full Learn Java course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Recursion in other languages
Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.
Lesson last updated on .