Avoiding
Stack Overflow
Learn how the call stack works in Java, why unbounded recursion crashes your program, and how to limit recursion depth to write safe, reliable code.
What Is the Call Stack?
Every time your Java program calls a method, the JVM pushes a new stack frame onto the call stack. Each frame stores the method's local variables, parameters, and the return address: where execution should resume when the method finishes.
What Is Recursion?
Recursion is when a method calls itself. It is a powerful technique for breaking problems into smaller, identical sub-problems. Every correct recursive method needs two parts:
Why Stack Overflow Happens
When recursion has no base case or the base case is never reached, each call adds a frame to the stack but none are ever removed. The stack grows until it exceeds its memory limit.
The Golden Rule of Recursion
If either condition is violated, the recursion becomes unbounded, and your program will crash with a StackOverflowError. Conceptually, think of recursion depth \( d \) as a countdown: every call must decrease \( d \) toward a known stopping point.
Anatomy of Safe Recursion
factorial(10000)? That is 10,000 frames: risky.Recursion vs Iteration
| Recursion | Iteration | |
|---|---|---|
| Memory | \( O(n) \) stack frames | \( O(1) \) constant |
| Overflow Risk | High for deep input | None |
| Readability | Elegant for trees, DFS | Simpler for linear tasks |
| Performance | Function call overhead | Faster loop execution |
| When to Use | Trees, divide-and-conquer | Loops, accumulators |
How to Limit Recursion Depth
Example: Depth-Limited Recursion
Example: Converting to Iteration
For linear recursion (one recursive call per method), you can always rewrite using a loop. This eliminates stack growth entirely.
Harder Example: Fibonacci
Fibonacci is a branching recursion: each call makes two recursive calls. This doubles the risk because depth can be \( n \) and total calls can be \( 2^n \).
Visualizing Branching Depth
Example: Binary Search
Recursive binary search on an array of \( n \) elements has maximum depth \( \log_2(n) \). Even for \( n = 10^9 \), the depth is only about 30: perfectly safe.
Safe vs Risky Recursion
| Safe | Risky | |
|---|---|---|
| Max Depth | \( O(\log n) \) | \( O(n) \) or unbounded |
| Examples | Binary search, merge sort | factorial(100000), DFS on long chain |
| Base Case | Always reached | May be missing or unreachable |
| Fix | No fix needed | Add depth limit or convert to iteration |
Common Mistakes
if check that stops recursion: the method calls itself forever.Question 1 of 5
What are the two essential parts of every correct recursive method?
Question 2 of 5
Consider this method:
public static void count(int n) {
System.out.println(n);
count(n);
}
What happens when count(5) is called?
count(n) with the same value, so \( n \) never changes. It prints 5 endlessly until the stack overflows.Question 3 of 5
Recursive binary search on an array of \( 10^9 \) elements has a maximum recursion depth of approximately:
Question 4 of 5
Which strategy completely eliminates stack overflow risk for a linear recursive computation?
StackOverflowError.Question 5 of 5
Consider this depth-limited method:
public static int f(int n, int depth) {
if (depth > 5000) throw new RuntimeException("Too deep");
if (n <= 1) return 1;
return n * f(n - 1, depth + 1);
}
What is the result of calling f(10000, 0)?
depth > 5000 triggers and throws a RuntimeException, unwinding the entire call stack. The depth limit prevents the computation from completing and avoids a StackOverflowError.