Tutorials Logic, IN info@tutorialslogic.com

StackOverflowError in Java: Causes, Fixes, Examples & Interview Tips

What is This Error?

The StackOverflowError is thrown when the JVM's call stack runs out of space. This typically happens due to infinite recursion "” a method that calls itself without a proper base case, causing the stack to grow until it overflows.

Common Causes

  • Recursive method without a base case
  • Base case that is never reached
  • Mutual recursion (method A calls B, B calls A)
  • Deeply nested data structures (very deep trees)
  • toString() calling itself indirectly

Quick Fix (TL;DR)

Quick Solution

Quick Solution
// ❌ Problem "” no base case
int factorial(int n) {
    return n * factorial(n - 1); // Infinite recursion!
}

// ✅ Solution "” add base case
int factorial(int n) {
    if (n <= 1) return 1; // Base case stops recursion
    return n * factorial(n - 1);
}

// ✅ Better "” use iteration for large n
long factorialIterative(int n) {
    long result = 1;
    for (int i = 2; i <= n; i++) result *= i;
    return result;
}

Common Scenarios & Solutions

Problem

Problem
int sum(int n) {
    return n + sum(n - 1); // ❌ No base case "” infinite recursion!
}

Solution

Solution
int sum(int n) {
    if (n <= 0) return 0; // ✅ Base case
    return n + sum(n - 1);
}

Problem

Problem
class Node {
    Node next;
    @Override
    public String toString() {
        return "Node{next=" + next + "}"; // ❌ Calls next.toString() → infinite if circular!
    }
}

Solution

Solution
class Node {
    int value;
    Node next;
    @Override
    public String toString() {
        // ✅ Don't recurse into next "” just show value
        return "Node{value=" + value + ", hasNext=" + (next != null) + "}";
    }
}

Solution

Solution
// Recursive Fibonacci (can overflow for large n)
int fibRecursive(int n) {
    if (n <= 1) return n;
    return fibRecursive(n - 1) + fibRecursive(n - 2);
}

// ✅ Iterative Fibonacci (no stack overflow)
long fibIterative(int n) {
    if (n <= 1) return n;
    long a = 0, b = 1;
    for (int i = 2; i <= n; i++) {
        long temp = a + b;
        a = b;
        b = temp;
    }
    return b;
}

// ✅ Or use explicit stack for tree traversal
void traverseIterative(TreeNode root) {
    Deque<TreeNode> stack = new ArrayDeque<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        System.out.println(node.value);
        if (node.right != null) stack.push(node.right);
        if (node.left != null) stack.push(node.left);
    }
}

Best Practices to Avoid This Error

  • Always define a base case - Every recursive method needs a termination condition
  • Verify the base case is reachable - Trace through your logic manually
  • Prefer iteration over recursion - For large inputs, iterative solutions are safer
  • Use memoization - Cache results to avoid redundant recursive calls
  • Use explicit stack for deep traversals - Replace recursion with a Stack/Deque
  • Increase JVM stack size if needed - Use -Xss flag (e.g., -Xss4m)
  • Be careful with toString() in linked structures - Avoid recursive printing

Related Errors

Frequently Asked Questions

It's caused by infinite recursion "” a method calling itself without a proper base case, or a base case that's never reached. Each method call adds a frame to the call stack, which eventually runs out of space.

Add or fix the base case in your recursive method. Verify the recursion actually moves toward the base case. Consider converting to an iterative solution for large inputs.

Yes, use the JVM flag -Xss: java -Xss4m MyProgram. But this is a workaround "” fixing the recursion logic is the proper solution.

Tail recursion is when the recursive call is the last operation in the method. Some languages optimize this to avoid stack growth, but Java does not perform tail call optimization.

Use a loop with an explicit Stack or Deque to simulate the call stack. Push items to process, pop and process them, push their children. This is the standard approach for tree/graph traversal.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.