Recursion
Recursion is when a method solves a problem by calling itself on a smaller version of the same problem. Every recursive method needs a base case that stops the chain.
Detailed Explanation
Some data is shaped like itself. A directory contains files and more directories. A binary tree node points at two smaller trees. A JSON object contains values that may be more objects. Writing a loop over a structure like that means managing your own stack of "where to go back to". Recursion lets the JVM manage that stack for you.
A recursive method has exactly two parts. The base case answers the smallest input directly and returns without calling itself. The recursive case reduces the input, calls itself, and combines the result. If the reduction does not strictly move toward the base case, the method never terminates.
Here is what actually happens at runtime. Each call pushes a stack frame holding that call's parameters, locals and return address. The frames stack up until a base case returns, then they unwind one by one, each combining its child's result. The maximum number of frames alive at once is the recursion depth, and that depth is your memory cost.
This is where Java differs from Scheme, Scala or Kotlin. The JVM does not perform tail-call elimination. A tail-recursive method, where the recursive call is the final action, still allocates a frame per call in Java. There is no keyword and no compiler flag that changes this. It has been a proposed JVM feature for many years and is still not shipped as of Java 21.
The practical consequence is a depth limit. The default thread stack is roughly 512 KB to 1 MB, which supports somewhere near ten to twenty thousand simple frames before StackOverflowError. Exact numbers vary with frame size, JVM flags and whether the method was JIT-compiled. That limit is comfortable for a balanced binary tree of a million nodes, since its depth is about 20. It is not comfortable for a linked list of 100,000 nodes, or a graph that happens to be one long chain.
So the rule: use recursion when the depth is bounded by something logarithmic or by the natural shape of the data. The exception: when depth can be linear in the input size, convert to an iterative loop with an explicit ArrayDeque as your stack. You can also raise the limit with -Xss4m, but that treats the symptom.
Recursion also has a performance trap that has nothing to do with the stack. Naive recursive Fibonacci recomputes the same subproblems over and over and runs in O(2^n). The fix is memoisation, which is the entry point to dynamic programming.
Where a learner meets recursion in interviews: tree traversals, merge sort and quicksort, permutations and subsets, flood fill on a grid, parsing nested expressions, and every backtracking problem. Costs are O(depth) stack space plus whatever the algorithm itself does, and a modest call overhead per invocation that the JIT often removes by inlining shallow calls.
Code Examples
public class TreeDepth {
// A record is enough to model an immutable binary tree node.
record Node(int value, Node left, Node right) {}
// Base case: an empty subtree has sum 0 and stops the recursion.
static int sum(Node node) {
if (node == null) return 0;
return node.value() + sum(node.left()) + sum(node.right());
}
// Depth is bounded by the height of the tree, so O(h) stack frames.
static int height(Node node) {
if (node == null) return 0;
return 1 + Math.max(height(node.left()), height(node.right()));
}
public static void main(String[] args) {
Node tree = new Node(1,
new Node(2, null, null),
new Node(3, new Node(4, null, null), null));
System.out.println(sum(tree)); // prints: 10
System.out.println(height(tree)); // prints: 3
}
}import java.util.ArrayDeque;
import java.util.Deque;
public class RecursionToIteration {
// Recursive: one frame per element, so a long list can overflow the stack.
static long sumRecursive(int[] values, int index) {
if (index == values.length) return 0;
return values[index] + sumRecursive(values, index + 1);
}
// Iterative with an explicit stack: heap memory grows instead of stack memory,
// and the heap is far larger. This is the standard rewrite for deep recursion.
static long sumIterative(int[] values) {
Deque<Integer> stack = new ArrayDeque<>();
for (int value : values) {
stack.push(value);
}
long total = 0;
while (!stack.isEmpty()) {
total += stack.pop(); // unboxes Integer back to int
}
return total;
}
public static void main(String[] args) {
int[] values = new int[100_000];
java.util.Arrays.fill(values, 1);
System.out.println(sumIterative(values)); // prints: 100000
try {
sumRecursive(values, 0);
} catch (StackOverflowError e) {
System.out.println("recursive version overflowed");
// prints: recursive version overflowed
}
}
}Common Gotchas
Java has no tail-call elimination
writing the recursive call in tail position does not save a frame on the JVM, unlike in Scala or Kotlin with `tailrec`. Depth still costs stack, and deep input still throws `StackOverflowError`.
A missing or unreachable base case never returns
if the recursive call does not strictly shrink the input, you get `StackOverflowError` rather than an infinite loop, because each call consumes stack. Check that every path toward the base case reduces the argument.
Recomputing subproblems is silently exponential
naive `fib(n)` is correct and takes `O(2^n)` calls. `fib(50)` will not finish. Add a memo array or rewrite bottom-up.
`StackOverflowError` is an `Error`, not an `Exception`
it is not caught by `catch (Exception e)`, and catching it leaves the thread in a state you should not keep using. Treat it as a design signal, not a recoverable condition.