StackOverflowError
JavaFATALNotableRuntime

Call stack depth exceeded

Quick Answer

Add a base case to recursive methods, or convert deep recursion to an iterative loop with an explicit stack.

What this means

Thrown when a thread's call stack overflows, almost always caused by unbounded or missing-base-case recursion.

Why it happens
  1. 1Recursive method with missing or unreachable base case
  2. 2Mutual recursion that never terminates

Fix

Convert recursion to iteration

Convert recursion to iteration
// Iterative (safe for deep n)
int sum(int n) {
    int total = 0;
    for (int i = n; i > 0; i--) total += i;
    return total;
}

Why this works

Iteration uses a fixed amount of stack space regardless of input size.

Code examples
Triggerjava
void infinite() { infinite(); } // StackOverflowError
Add base casejava
int factorial(int n) {
    if (n <= 1) return 1; // base case
    return n * factorial(n - 1);
}
Explicit stack for deep recursionjava
Deque<Node> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
    Node n = stack.pop();
    // process n, push children
}
Sources
Official documentation ↗

Java SE Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Java errors