Skip to content

Module 4 · Methods — topic 3 of 3

Recursion

Methods that call themselves: base cases and recursive cases, the call stack, classic examples, memoisation, and when to prefer iteration.

Beginner 18 min read·Lesson 15 of 39 in Java Programming

Learning objectives

  • Identify the base case and recursive case of a problem
  • Trace recursive calls on the call stack
  • Improve exponential recursion with memoisation

Definition

Recursion is a technique in which a method solves a problem by calling itself on smaller instances of the same problem until it reaches a base case that can be answered directly.

Introduction

Some problems are naturally defined in terms of themselves. The factorial of n is n times the factorial of n − 1; the files in a folder are the files directly inside it plus the files in each sub-folder. Recursion lets your code follow that definition directly.

Why it matters

Trees, graphs, file systems, sorting algorithms such as merge sort and quicksort, and backtracking puzzles are all expressed most clearly with recursion.

Recursion questions are a staple of programming interviews.

Detailed explanation

Every recursive method needs a base case that returns without recursing, and a recursive case that moves towards the base case. Without the base case — or if the arguments don't get smaller — the recursion never ends.

Each call gets its own stack frame holding its parameters and local variables. When the base case returns, the frames unwind one by one, each finishing its own computation.

The stack has a limited size (typically a few thousand to tens of thousands of frames). Recursing too deeply throws StackOverflowError. Java does not optimise tail calls, so a deeply recursive loop should be rewritten iteratively.

Naive recursion can repeat work: computing Fibonacci with fib(n - 1) + fib(n - 2) makes an exponential number of calls. Memoisation stores each answer the first time it is computed (in an array or map), turning exponential time into linear time.

Divide and conquer splits a problem into halves, solves each recursively and combines the results — binary search, merge sort and fast exponentiation all work this way.

Any recursion can be converted into a loop (sometimes with an explicit stack). Prefer recursion when it makes the code clearly simpler, and iteration when depth could be large.

Syntax

Java
static long factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
  • Make sure every recursive call moves closer to a base case.
  • Check invalid input (such as negative n) before recursing.
  • Use long or BigInteger when results grow quickly.

Code examples

Factorial, sum of digits and power

Java
public class Rec {
static long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
static int digitSum(int n) {
if (n < 10) return n;
return n % 10 + digitSum(n / 10);
}
static long power(long base, int exp) { // divide and conquer: O(log exp)
if (exp == 0) return 1;
long half = power(base, exp / 2);
return exp % 2 == 0 ? half * half : half * half * base;
}
public static void main(String[] args) {
System.out.println(factorial(5) + " " + factorial(20));
System.out.println(digitSum(98765));
System.out.println(power(2, 10) + " " + power(3, 13));
}
}
Output
120 2432902008176640000
35
1024 1594323

Watching the call stack

Java
public class Trace {
static int countdown(int n, int depth) {
String indent = " ".repeat(depth);
System.out.println(indent + "enter " + n);
int result = n == 0 ? 0 : n + countdown(n - 1, depth + 1);
System.out.println(indent + "return " + result);
return result;
}
public static void main(String[] args) {
countdown(3, 0);
}
}
Output
enter 3
  enter 2
    enter 1
      enter 0
      return 0
    return 1
  return 3
return 6

More examples

Memoised Fibonacci, binary search and permutations

Java
import java.util.ArrayList;
import java.util.List;
public class Recursion {
static int calls = 0;
static long fibNaive(int n) {
calls++;
return n < 2 ? n : fibNaive(n - 1) + fibNaive(n - 2);
}
static long fibMemo(int n, long[] memo) {
if (n < 2) return n;
if (memo[n] != 0) return memo[n];
return memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
}
static int binarySearch(int[] a, int target, int lo, int hi) {
if (lo > hi) return -1;
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) return mid;
return a[mid] < target ? binarySearch(a, target, mid + 1, hi) : binarySearch(a, target, lo, mid - 1);
}
static void permute(String prefix, String rest, List<String> out) {
if (rest.isEmpty()) { out.add(prefix); return; }
for (int i = 0; i < rest.length(); i++)
permute(prefix + rest.charAt(i), rest.substring(0, i) + rest.substring(i + 1), out);
}
public static void main(String[] args) {
System.out.println("fib(25) = " + fibNaive(25) + " using " + calls + " calls");
System.out.println("fib(90) = " + fibMemo(90, new long[91]));
int[] sorted = {3, 8, 15, 23, 42, 57, 91};
System.out.println("index of 42: " + binarySearch(sorted, 42, 0, sorted.length - 1) + ", of 5: " + binarySearch(sorted, 5, 0, sorted.length - 1));
List<String> perms = new ArrayList<>();
permute("", "abc", perms);
System.out.println(perms);
}
}
Output
fib(25) = 75025 using 242785 calls
fib(90) = 2880067194370816120
index of 42: 4, of 5: -1
[abc, acb, bac, bca, cab, cba]

Step-by-step explanation

  • fibNaive recomputes the same values again and again: 242,785 calls just for fib(25).
  • fibMemo stores each result in memo; every value from 2 to 90 is computed once, so fib(90) is instant.
  • binarySearch halves the range on every call and stops when lo > hi (not found) or the middle element matches.
  • lo + (hi - lo) / 2 computes the midpoint without overflowing for very large indexes.
  • permute fixes each remaining character in turn and recurses on the others; the base case adds a finished permutation to the list.

Expected output

Running “Memoised Fibonacci, binary search and permutations” prints exactly:

TextOutput
fib(25) = 75025 using 242785 calls
fib(90) = 2880067194370816120
index of 42: 4, of 5: -1
[abc, acb, bac, bca, cab, cba]

Practical applications

  • Walking directory trees and parsing nested data such as JSON or XML
  • Sorting with merge sort and quicksort
  • Backtracking solvers for Sudoku, mazes and N-Queens
  • Evaluating expression trees in compilers and calculators

Best practices

  • Write the base case first.
  • Use memoisation whenever the same arguments recur.
  • Convert to iteration when recursion depth can reach thousands.

Common mistakes

No base case or no progress

Avoid

static int sum(int n) { return n + sum(n - 1); }

Prefer

static int sum(int n) { return n <= 0 ? 0 : n + sum(n - 1); }

Without a base case the method calls itself until the stack overflows.

Exponential recursion on large inputs

Avoid

fibNaive(50) // billions of calls

Prefer

fibMemo(50, new long[51]) // 49 additions

Overlapping subproblems must be cached; otherwise the running time grows exponentially.

Important notes

  • The default thread stack can usually hold around 10,000 simple frames, but the exact limit depends on the JVM and the frame size.
  • fib(93) overflows long; use java.math.BigInteger for larger values.

Key takeaways

  • Recursion needs a base case and progress towards it.
  • Each call has its own stack frame; too many cause StackOverflowError.
  • Memoisation removes repeated work in overlapping recursions.

Try it yourself

  1. 1
    Write a recursive method that reverses a string.
  2. 2
    Solve the Tower of Hanoi for n disks and print each move; how many moves are needed for n = 10?

Finished reading? Mark it complete to update your dashboard.

Suggested practice

9 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat happens if a recursive method has no reachable base case?
  • BeginnerWhat is printed?
Practise this topic