Recursion depth and StackOverflowError
28 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A mathematically correct recursive method with a valid base case can still crash in production with java.lang.StackOverflowError if its recursion depth is too large! Knowing when recursion depth is safe (O(log n)) vs dangerous (O(n) for large n), why Java does not optimize tail calls, and how to convert recursion into iteration will save your code on large inputs.
Stack size depends on the JVM and its settings
The call stack is the memory where Java keeps one frame for every method call that has not finished yet. Too many nested calls fill it and cause StackOverflowError.
Each Java thread gets a fixed-size memory buffer for its call stack when the thread starts. In standard 64-bit OpenJDK / HotSpot (Java 17), the default thread stack size is typically 1 MB (1024 KB, configurable via the JVM flag -Xss, e.g., java -Xss8m Main).
Example 1 · Catching StackOverflowError to see the default JVM recursion depth limit
public class RecursionDepthCheckDemo { public static int safeDivideAndConquer(int lo, int hi, int depth) { if (lo == hi) return depth; int mid = lo + (hi - lo) / 2; return Math.max(safeDivideAndConquer(lo, mid, depth + 1), safeDivideAndConquer(mid + 1, hi, depth + 1)); }
public static void main(String[] args) { // Divide and conquer on n = 1,000,000 elements only reaches depth 21! int maxD = safeDivideAndConquer(0, 999_999, 1); System.out.println("Divide-and-conquer depth for n=1,000,000: " + maxD);
// Meanwhile, linear recursion on n=1,000,000 would need 1,000,000 frames (unsafe!). // Iterative loop handles n=1,000,000 in 1 stack frame: long sum = 0; for (int i = 1; i <= 1_000_000; i++) sum += i; System.out.println("Iterative sum for n=1,000,000: " + sum); }}Divide-and-conquer depth for n=1,000,000: 21 Iterative sum for n=1,000,000: 500000500000
What this code does
- For n = 1,000,000, divide-and-conquer uses only 21 stack frames, whereas linear recursion would need 1,000,000 frames and throw StackOverflowError.
- An iterative loop uses just 1 stack frame regardless of how large n is.
- Logarithmic depth O(log n) (Binary Search, Merge Sort, balanced trees): even for n = 10⁹, depth is ≤ 30 frames — always safe!
- Small linear depth n ≤ 2,000: linear recursion of depth 2,000 is typically safe.
- Large linear depth n ≥ 10⁴ (e.g., DFS on a graph or skewed tree with n = 10⁵ nodes, or linear array recursion): will crash with
StackOverflowErroron default JVM stack settings—use an iterative loop or explicitArrayDequestack!
How many stack frames fit in 1 MB? It depends on how many parameters and local variables each frame has and whether the method has been JIT-compiled, but in practice on a default 1 MB stack, a recursive method crashes with StackOverflowError somewhere around 8,000 to 20,000 nested calls! Use problem constraints as your safety gauge:
Java does not optimise tail calls
A recursive call is in tail position (a tail call) when calling itself is the very last action the method performs before returning—nothing is added or multiplied after the recursive call returns:
- Not tail-recursive:
public class NoTailCallOptimisation { static long sumTail(long n, long acc) { if (n == 0) return acc; return sumTail(n - 1, acc + n); // tail call: nothing left to do after it }
public static void main(String[] args) { System.out.println(sumTail(10, 0)); try { sumTail(10_000_000, 0); } catch (StackOverflowError e) { System.out.println("StackOverflowError: Java kept every frame"); } }}55 StackOverflowError: Java kept every frame
return n * fact(n - 1); (must keep frame alive to multiply by n after fact(n - 1) returns).
- Tail-recursive:
return factTail(n - 1, n * acc);(passes running productaccforward; nothing left to do on return).
Some languages (like Scheme, Haskell, or Kotlin with the tailrec keyword) perform Tail-Call Optimization (TCO): the compiler reuses the current stack frame for a tail call in O(1) space. Java (javac and the HotSpot JVM in Java 17) does NOT perform tail-call elimination (largely to preserve accurate stack traces for debugging and security stack walks). In Java, a tail-recursive method still pushes n stack frames and still throws StackOverflowError for large n!
Find the bug
Spot the recursion bug
Each method has one wrong line. Tap the line to fix, then check.
Sum of 1..n. It ends with a StackOverflowError.
Round 1 of 3while loop in 30 seconds!Turning recursion into a loop
There are two ways to convert recursion into iteration with O(1) call-stack usage.
Example 2 · Converting tail recursion mechanically into a while loop
public class TailToLoopDemo { // 1. Non-tail recursive: multiplies AFTER the recursive call public static long factNonTail(int n) { if (n <= 1) return 1L; return n * factNonTail(n - 1); }
// 2. Tail-recursive: passes accumulator forward (still O(n) stack in Java!) public static long factTail(int n, long acc) { if (n <= 1) return acc; return factTail(n - 1, acc * n); }
// 3. Direct mechanical translation of factTail into a while loop (O(1) stack!) public static long factIterative(int n) { long acc = 1L; while (n > 1) { acc = acc * n; n = n - 1; } return acc; }
public static void main(String[] args) { System.out.println(factNonTail(12) + " " + factTail(12, 1L) + " " + factIterative(12)); }}479001600 479001600 479001600
What this code does
- Look at factTail vs factIterative: if (n <= 1) return acc becomes while (n > 1), and the tail call arguments (n - 1, acc * n) become assignments inside the loop!
- factIterative uses O(1) space and never risks StackOverflowError.
Example 3 · Replacing deep branching recursion with an explicit ArrayDeque stack on the heap
import java.util.ArrayDeque;import java.util.Deque;
public class ExplicitHeapStackDemo { // Computes sum of [lo..hi] using an explicit stack on the heap instead of the JVM call stack public static long rangeSumExplicitStack(int[] arr) { Deque<int[]> stack = new ArrayDeque<>(); stack.push(new int[]{0, arr.length - 1}); long total = 0;
while (!stack.isEmpty()) { int[] range = stack.pop(); int lo = range[0], hi = range[1]; if (lo == hi) { total += arr[lo]; } else { int mid = lo + (hi - lo) / 2; stack.push(new int[]{mid + 1, hi}); stack.push(new int[]{lo, mid}); } } return total; }
public static void main(String[] args) { int[] arr = {10, 20, 30, 40, 50}; System.out.println("Explicit stack sum: " + rangeSumExplicitStack(arr)); }}Explicit stack sum: 150
What this code does
- Pushing mid + 1..hi first and lo..mid second makes stack.pop() process the left half first, matching recursive depth-first order.
- Because ArrayDeque lives on the JVM heap, it can hold millions of elements without overflowing the 1 MB thread call stack.
In detail:
- Tail recursion → simple
whileloop (O(1) space):
Replace the base case if (cond) return acc; with while (!cond), update the accumulator and parameters inside the loop body, and return acc after the loop!
- Branching / non-tail recursion (like DFS on a deep graph or tree) → explicit
Dequeon the heap (O(n) heap space):
Because the JVM heap is hundreds of megabytes or gigabytes (whereas the thread call stack is only 1 MB), pushing nodes onto Deque<Node> stack = new ArrayDeque<>() on the heap handles 10⁶ depth without ever throwing StackOverflowError!
Next step
Check your understanding
10 quick questions