Skip to lesson

Recursion refresher

A method is recursive when it solves a problem by calling itself on a strictly smaller instance of the same problem. Before tackling backtracking, trees, and divide-and-conquer, you need a crystal-clear mental model of how the JVM call stack winds down to a base case and unwinds with return values.

Base case and recursive case

Recursion is a method calling itself on a smaller version of the same problem until it reaches a base case that is answered directly.

A recursive method is a method that calls itself. Every working recursive method has two essential parts.

Java
static long factorial(int n) {    if (n <= 1) return 1;          // base case: answer known at once    return n * factorial(n - 1);   // recursive case: a smaller input}
  1. Base case: the smallest input(s) where the answer is known immediately without making another recursive call (for example, 0! = 1, or an empty subarray of length 0).
  2. Recursive case: breaks the current input of size n into one or more smaller subproblems (such as n - 1 or n / 2), calls the method on those smaller inputs, and combines their results.

If you forget the base case—or if your recursive call does not strictly move toward the base case (for example, calling fact(n) instead of fact(n - 1), or calling fact(-1) when the base case only checks n == 0)—the calls never stop until the JVM throws StackOverflowError!

  • Always write and test the base case first at the very top of the method.
  • Guard against invalid or edge inputs (e.g., if (n <= 1) return 1; instead of if (n == 1) when n = 0 is a valid input).
  • Verify that every recursive call strictly shrinks the distance to the base case.

How the call stack grows

A base case is the simplest input that a recursive method answers without calling itself. Without one, recursion never stops.

When method A calls method B—or when factorial(4) calls factorial(3)—the JVM pushes a stack frame (activation record) onto the current thread's call stack.

Example 1 · Visualizing the winding and unwinding phases on the call stack

StackTraceVisualizerDemo.javaJava
public class StackTraceVisualizerDemo {    public static long factorialWithTrace(int n, int depth) {        String indent = "  ".repeat(depth);        System.out.println(indent + "-> enter factorial(" + n + ")");        if (n <= 1) {            System.out.println(indent + "<- base case factorial(" + n + ") = 1");            return 1L;        }        long sub = factorialWithTrace(n - 1, depth + 1);        long result = n * sub;        System.out.println(indent + "<- return factorial(" + n + ") = " + n + " * " + sub + " = " + result);        return result;    }
    public static void main(String[] args) {        factorialWithTrace(4, 0);    }}
Output
-> enter factorial(4)
  -> enter factorial(3)
    -> enter factorial(2)
      -> enter factorial(1)
      <- base case factorial(1) = 1
    <- return factorial(2) = 2 * 1 = 2
  <- return factorial(3) = 3 * 2 = 6
<- return factorial(4) = 4 * 6 = 24

What this code does

  • The '-> enter' lines print during the winding phase (4 -> 3 -> 2 -> 1).
  • The '<- return' lines print during the unwinding phase (1 -> 2 -> 3 -> 4) as each paused frame multiplies its own n by the returned sub-result.

Example 2 · Pre-call work vs post-call work: printing n..1 vs 1..n

PreVsPostCallDemo.javaJava
public class PreVsPostCallDemo {    public static void printBothWays(int n) {        if (n == 0) {            System.out.print("| ");            return;        }        System.out.print(n + " "); // pre-call (winding: n down to 1)        printBothWays(n - 1);        System.out.print(n + " "); // post-call (unwinding: 1 up to n)    }
    public static void main(String[] args) {        printBothWays(4);        System.out.println();    }}
Output
4 3 2 1 | 1 2 3 4 

What this code does

  • Statements placed BEFORE the recursive call execute in lifo/top-down order (4, 3, 2, 1).
  • Statements placed AFTER the recursive call execute as the stack unwinds in bottom-up order (1, 2, 3, 4).

Example 3 · Sum of digits of a non-negative integer using recursion

SumOfDigitsRecursiveDemo.javaJava
public class SumOfDigitsRecursiveDemo {    public static int sumDigits(int n) {        if (n < 10) {            return n; // base case: single-digit number        }        return (n % 10) + sumDigits(n / 10);    }
    public static void main(String[] args) {        System.out.println("sumDigits(7) = " + sumDigits(7));        System.out.println("sumDigits(4928) = " + sumDigits(4928));    }}
Output
sumDigits(7) = 7
sumDigits(4928) = 23

What this code does

  • n % 10 peels off the last digit (8), and n / 10 shrinks the number to 492.
  • 4928 -> 8 + sumDigits(492) -> 8 + 2 + sumDigits(49) -> 8 + 2 + 9 + 4 = 23.

That stack frame stores the call's own local variables, parameters (n = 4), and the return address where execution will resume once the inner call finishes. Crucially, factorial(4) and factorial(3) do not share the parameter n: each stack frame has its own independent copy of n! Execution happens in two phases:

  • Winding (pushing) phase: work done before the recursive call executes top-down as frames are pushed onto the stack.
  • Unwinding (popping) phase: work done after the recursive call executes bottom-up in reverse order as frames return and pop off the stack.
In a simplified mental model, think of the call stack as a stack of sticky notes: each recursive call places a new note on top and pauses the note underneath until the top note finishes and hands back its answer.

Tracing factorial

Let us hand-trace factorial(4) where factorial(n) returns 1 if n <= 1 and n * factorial(n - 1) otherwise:

  1. factorial(4) needs 4 * factorial(3) -> pauses and pushes factorial(3).
  2. factorial(3) needs 3 * factorial(2) -> pauses and pushes factorial(2).
  3. factorial(2) needs 2 * factorial(1) -> pauses and pushes factorial(1).
  4. factorial(1) hits the base case (n <= 1) and returns 1 (peak stack depth = 4 frames).
  5. factorial(2) resumes: computes 2 * 1 = 2 and returns 2.
  6. factorial(3) resumes: computes 3 * 2 = 6, and factorial(4) computes 4 * 6 = 24.

Predict the output

Trace the recursive calls

Work out the calls on paper, then pick what each program prints.

Round 1 of 2

Factorial of 4.

public class FactTrace {
static int f(int n) {
if (n == 1) return 1;
return n * f(n - 1);
}
public static void main(String[] args) {
System.out.println(f(4));
}
}

How to spot this pattern

Reach for recursion when a problem contains a smaller copy of itself. Look for these clues in the problem.

  • The problem is described in terms of itself: a folder that holds folders, n and n - 1, a tree of replies.
  • The input splits into a first piece and "the rest", or into two halves that you can solve the same way.
  • You can name the simplest case that needs no more work (empty list, n = 0, one element): that is the base case.
  • The input is a tree, a nested structure or an "all ways to..." question: recursion is usually the cleanest fit.

Next step

Check your understanding

10 quick questions