Skip to content
Codewilds

Lesson 11 of 34 · Methods

Java Recursion: Methods That Call Themselves

medium20 XP3 min read

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) when n starts negative).
  • Not shrinking the input: factorial(n) inside factorial recurses forever; it must be factorial(n - 1).
  • Forgetting return: calling factorial(n - 1); without using its result throws the answer away.
  • Overflowing int: factorials grow fast. 13! no longer fits in an int, so use long.

Assignment

Write four recursive methods in Main (no loops):

  1. factorial(int n) returns n! as a long (n ≥ 0): factorial(5) is 120, factorial(0) is 1, factorial(20) is 2432902008176640000.
  2. power(int base, int exponent) returns base raised to exponent as a long (exponent ≥ 0): power(2, 10) is 1024, power(5, 0) is 1.
  3. sumDigits(int n) returns the sum of the digits of n (n ≥ 0): sumDigits(4096) is 19.
  4. isPalindrome(String s) returns true if s reads 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
Play the 8 free lessons

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 .

Write code ↓
Java+20 XP

Lesson 11 is part of the full course. The first 8 lessons are free.

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
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.