Recursion in Java
Write self-calling methods that break problems into smaller versions of themselves — base case, recursive case, and call stack mechanics.
Write self-calling methods that break problems into smaller versions of themselves — base case, recursive case, and call stack mechanics.
Recursion
Recursion is when a method calls itself to solve a smaller version of the same problem. Every recursive algorithm needs two parts: a base case that stops the recursion, and a recursive case that breaks the problem down further.
Introduction
Recursion is a way for a method to solve a problem by calling itself on smaller parts of the input. Tree traversal, divide-and-conquer sorting, and combinatorial generation can fit this pattern. Factorial is one example: factorial(n) = n * factorial(n-1). A loop can compute the same result with an accumulator; which version is easier to follow depends on the problem and the code around it.
Every recursive algorithm needs a base case that stops and returns a result, plus a recursive case that makes progress toward it. If the calls do not reach the base case, the call chain can exhaust the available stack and throw StackOverflowError. Stack capacity depends on the JVM, platform, and configuration, so there is no portable safe recursion depth. Java does not guarantee tail-call optimization; do not assume a tail-recursive method uses constant stack space.
This post covers base cases, recursive progress, and how active calls use the call stack. Naive Fibonacci is slow because it recomputes the same subproblems; memoization helps here because those results repeat. The examples also compare recursion with loops and explicit stacks for traversals whose depth may be large or controlled by external input.
When to Use
- Problems that can be naturally expressed as “solve the same problem on a smaller input”
- Tree traversal, graph traversal, divide-and-conquer algorithms
- When the iterative equivalent would require explicit stack management
When Not to Use
- When a simple loop expresses the steps more clearly
- When input can produce a deep call chain, especially if that depth is untrusted or hard to bound
- When the problem naturally reduces to iteration and the recursive version offers no clarity benefit
Anatomy of a Recursive Method
public int factorial(int n) {
// Base case — stop condition
if (n <= 1) return 1;
// Recursive case — call itself with smaller input
return n * factorial(n - 1);
}
| Component | Role |
|---|---|
| Base case | Condition where recursion stops — must be reachable |
| Recursive case | Call to itself with a reduced/different input |
| Call stack | Each call gets its own stack frame with local variables |
How the Call Stack Works
public void countdown(int n) {
if (n <= 0) return;
System.out.println(n);
countdown(n - 1);
}
Each recursive call adds a stack frame. When the base case is hit, the stack unwinds — each frame completes and returns to its caller.
countdown(3)
print 3
countdown(2)
print 2
countdown(1)
print 1
countdown(0) → returns (base case)
returns
returns
returns
Iterative Alternative for Deep Structures
When a nested structure may be very deep, an explicit worklist avoids using one Java call frame per level. This preorder traversal visits children from left to right:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
public class IterativeTreeTraversal {
record Node(String name, List<Node> children) {}
public static void main(String[] args) {
Node root = new Node("root", List.of(
new Node("left", List.of()),
new Node("right", List.of())
));
printPreorder(root);
}
static void printPreorder(Node root) {
Deque<Node> pending = new ArrayDeque<>();
pending.push(root);
while (!pending.isEmpty()) {
Node current = pending.pop();
System.out.println(current.name());
List<Node> children = current.children();
for (int i = children.size() - 1; i >= 0; i--) {
pending.push(children.get(i));
}
}
}
}
The deque moves pending traversal state to heap memory; it does not remove the need to manage resources. For untrusted input, set application-specific limits on nodes or work, and account for the worklist’s memory use.
Mermaid Diagram — Call Stack for Factorial(4)
flowchart TD
A["factorial(4)"] --> B["4 * factorial(3)"]
B --> C["3 * factorial(2)"]
C --> D["2 * factorial(1)"]
D --> E["returns 1 (base case)"]
E --> D
D --> C
C --> B
B --> A
A --> F["returns 24"]
Failure Scenarios
Missing or incorrect base case — StackOverflowError:
// WRONG — no base case, infinite recursion
public int badRecursive(int n) {
return n + badRecursive(n - 1); // StackOverflowError
}
Base case not reachable — also StackOverflowError:
// WRONG — base case exists but recursive call never reaches it
public int infiniteRecursion(int n) {
if (n == 0) return 0;
return n + infiniteRecursion(n); // n never changes — infinite loop on stack
}
Integer overflow with large inputs:
public int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1); // for n > 12, result exceeds int range
}
// factorial(13) = 6227020800 — overflows int, returns negative
Tail recursion does not guarantee constant stack use in Java:
// This is tail recursion — last operation is the recursive call itself
// Java does not guarantee tail-call optimization
public int tailFactorial(int n, int accumulator) {
if (n <= 1) return accumulator;
return tailFactorial(n - 1, n * accumulator); // do not assume constant stack use
}
Trade-off Table
| Aspect | Recursion | Iteration |
|---|---|---|
| Readability | Can follow the structure of trees and divide-and-conquer work | Can make linear processing and depth limits explicit |
| Memory | Call-stack use depends on maximum call depth | A simple loop may use constant extra space; explicit worklists use memory |
| Speed | Depends on the algorithm, JVM, and workload | Depends on the algorithm, JVM, and workload; measure if it matters |
| Stack overflow risk | Deep call chains can exhaust the available stack | Avoids recursive call depth; a worklist can still grow |
| Debugging | Call stacks reflect nested calls | Loop state or an explicit worklist is visible |
Code Snippets
Binary search (divide and conquer):
public int binarySearch(int[] sorted, int target) {
return binarySearch(sorted, target, 0, sorted.length - 1);
}
private int binarySearch(int[] arr, int target, int low, int high) {
if (low > high) return -1; // base case: not found
int mid = (low + high) / 2;
if (arr[mid] == target) return mid; // found
else if (arr[mid] < target) return binarySearch(arr, target, mid + 1, high); // right half
else return binarySearch(arr, target, low, mid - 1); // left half
}
Merge sort:
public void mergeSort(int[] arr, int left, int right) {
if (left >= right) return; // base case: single element
int mid = (left + right) / 2;
mergeSort(arr, left, mid); // sort left half
mergeSort(arr, mid + 1, right); // sort right half
merge(arr, left, mid, right); // merge sorted halves
}
Fibonacci — memoization avoids repeating the same subproblems:
public class Fibonacci {
private static long[] memo = new long[100]; // cache
public static long fib(int n) {
if (n <= 1) return n;
if (memo[n] != 0) return memo[n]; // return cached
return memo[n] = fib(n - 1) + fib(n - 2); // cache and return
}
}
Observability Checklist
- Base case is clearly defined and always reachable
- Each recursive call makes measurable progress toward the base case
- Check how input size affects maximum call depth; use iteration or an explicit worklist when depth is untrusted
- Memoize when the algorithm revisits the same subproblems; otherwise the cache may add overhead without avoiding work
- Naive Fibonacci recomputes overlapping subproblems; use memoization or iterative dynamic programming instead of a fixed input cutoff
- Recursive algorithms that can be expressed iteratively should consider that option
Security Notes
- Available stack depends on the JVM and platform; deep recursion can cause
StackOverflowError - Deep or cyclic untrusted structures can consume stack, heap, or processing time
- For untrusted input, use an iterative traversal where appropriate and enforce application-specific limits on depth, nodes, or work
- Deep file-system walks over untrusted trees can consume substantial work; prefer an iterative walk with limits when the input is not controlled
Pitfalls
- Stack overflow from unbounded recursion — always verify the base case and progress condition
- Repeated work in naive Fibonacci — memoization helps because the same values are recomputed; an iterative solution also avoids that work
- Assuming tail recursion uses constant stack space — Java does not guarantee tail-call optimization
- Integer overflow in factorial —
factorial(13)overflowsint,factorial(21)overflowslong - Mutating shared state during recursion — can cause incorrect results when multiple stack frames affect the same variable
Quick Recap
- Every recursive method needs a reachable base case and a recursive case that reduces toward it
- Active recursive calls use stack space — a sufficiently deep chain risks
StackOverflowError - Java does not guarantee tail-call optimization, so tail recursion is not a promise of constant stack use
- Memoization helps when recursive calls repeat subproblems, as in naive Fibonacci; iterative dynamic programming is another option
- Divide-and-conquer problems (binary search, merge sort) are natural fits for recursion
Interview Questions
Further Reading
- Static Methods — static methods and their stack behavior
- Variable Scope — local variables and stack frames
- Method Overloading — compile-time resolution vs runtime dispatch
- Lambda Expressions — functional recursion patterns
- Java Records Guide — records for clean base case returns
- StackOverflowError API — when Java throws this error
- JVM Specification: Java Virtual Machine Stacks — stack behavior and implementation choices
- Java launcher
-Xssoption — configuring HotSpot thread stack size
Conclusion
Recursion can make tree traversal and divide-and-conquer algorithms easier to follow. Every recursive method needs a reachable base case and a recursive case that makes progress toward it.
Each unresolved recursive call contributes to stack depth, and a chain that exceeds the available stack can throw StackOverflowError. There is no portable maximum depth, so use an iterative traversal with explicit resource limits when external input can be deeply nested. Memoization reduces work only when recursive calls repeat subproblems; naive Fibonacci is one example. Performance and memory use depend on the algorithm and runtime, so measure them on the target workload when they matter.
Divide-and-conquer algorithms and tree-based problems often map cleanly to recursion. An explicit stack can make traversal depth and pending work easier to control when input size is unpredictable.
For more on related patterns: Static Methods covers how class-level methods work without instance state, and Variable Scope explains how local variables and stack frames interact during method execution.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.