01 / 20

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.

Java

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.

main() methodA() methodB() methodC() TOP BOTTOM Each call adds a frame

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:

Base Case
A condition that stops the recursion. Without it, the method calls itself forever.
Recursive Case
The step that reduces the problem and calls the method again with a smaller input.

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.

f(5) f(4) f(3) f(2) f(1)
\( f(0) \dots f(-\infty) \)
StackOverflowError Stack keeps growing

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.

0 base case 1 2 3
\( n \)
start each call decreases depth by 1

Anatomy of Safe Recursion

public static int factorial(int n) { // Base case: stops recursion if (n <= 1) { return 1; } // Recursive case: n decreases each call return n * factorial(n - 1); }
✓ Base Case
\( n \leq 1 \) returns immediately: no more calls.
✓ Convergence
\( n - 1 \) is strictly smaller, so it always reaches the base case.
✓ Max Depth
Depth is exactly \( n \) frames. Call 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

1
Identify the base case. Determine what condition should stop the recursion entirely.
2
Ensure convergence. Verify that each recursive call makes progress toward the base case (e.g., \( n \) decreases).
3
Add a depth parameter. Pass a counter or depth limit to the method; if it exceeds the limit, return a safe default or throw an exception.
4
Consider converting to iteration. If the problem is linear (not branching), rewrite with a loop to avoid stack use entirely.

Example: Depth-Limited Recursion

static final int MAX_DEPTH = 10000; public static long safeFact(int n, int depth) { if (depth > MAX_DEPTH) { throw new IllegalArgumentException( "Recursion too deep"); } if (n <= 1) return 1; return n * safeFact(n - 1, depth + 1); }

Example: Converting to Iteration

For linear recursion (one recursive call per method), you can always rewrite using a loop. This eliminates stack growth entirely.

// Recursive version public static long factRec(int n) { if (n <= 1) return 1; return n * factRec(n - 1); } // Iterative version: \( O(1) \) stack space public static long factIter(int n) { long result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; }

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 \).

// Dangerous: exponential calls, deep stack public static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } // Safe: iterative, \( O(1) \) stack public static int fibIter(int n) { if (n <= 1) return n; int a = 0, b = 1; for (int i = 2; i <= n; i++) { int temp = a + b; a = b; b = temp; } return b; }

Visualizing Branching Depth

fib(4) fib(3) fib(2) fib(2) fib(1)=1 fib(1)=1 fib(0)=0 fib(1) fib(0) depth 0 depth 1 depth 2 depth 3 Max stack depth = 4 frames for fib(4) For fib(10000), depth = 10000: overflow

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.

public static int binarySearch(int[] arr, int target, int lo, int hi) { if (lo > hi) return -1; // base case int mid = lo + (hi - lo) / 2; if (arr[mid] == target) return mid; if (arr[mid] < target) return binarySearch(arr, target, mid+1, hi); return binarySearch(arr, target, lo, mid-1); }

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

✕ No Base Case
Forgetting the if check that stops recursion: the method calls itself forever.
✕ Non-Converging Input
Passing the same or larger value: e.g., \( f(n) \) calls \( f(n) \) instead of \( f(n-1) \).
✕ Ignoring Input Size
Using recursion for \( n = 10^6 \) without checking if depth exceeds the stack limit.

Question 1 of 5

What are the two essential parts of every correct recursive method?

Question 2 of 5

What happens when count(5) is called?

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?

Question 5 of 5

What is the result of calling f(10000, 0)?