RadhaPublication
HomeInterviewLearning PathsRole TracksMockBooksPricing
Login / Sign UpLog in

© 2026 Radha Publication. All rights reserved.

Shop on AmazonDonateContactPrivacyTerms
Java questions
EasyJava#86 min readJul 11, 2026

What is StackOverflowError?

practice
learning
Practice modeTest yourself instead of reading straight through

Hook: Interviewers love this question because it checks whether you understand Java memory, recursion, and how one small bug can crash a thread.

Question: What is StackOverflowError?

Answer: StackOverflowError is a Java Error thrown when a thread uses up its call stack, usually because of infinite recursion or extremely deep method calls. A stack frame is the small memory block a method needs for its parameters, local variables, and return information. When there is no more room for another frame, the JVM stops that thread with this error.

Interview-Ready Answer: I would say that StackOverflowError happens when a thread runs out of stack space, most often from missing or wrong base cases in recursion. Each method call adds a stack frame, and when the stack is full the JVM throws this Error. In Java, the practical fix is to stop the unbounded recursion, reduce call depth, or switch to an iterative solution; increasing -Xss only gives more stack, it does not fix the bug.

🧠 Memory Map
Memory map — visual summary of this topic

What it is

StackOverflowError is a subclass of VirtualMachineError, which means the JVM considers it a serious runtime problem, not a normal business-rule failure. In simple words: the thread's call stack is full. The call stack is the memory area that stores active method calls, and each call adds a stack frame holding parameters, local variables, and the place to return after the method finishes.

How it happens under the hood

  1. A thread enters a method, so the JVM pushes one stack frame for that call.
  2. That method calls another method, so a second frame is pushed on top.
  3. If the code keeps recursing, frames keep piling up instead of being reused.
  4. Every stack has a fixed size. In HotSpot, the default is platform-dependent, but many 64-bit JVMs reserve around 1 MB per thread.
  5. When the JVM cannot reserve space for the next frame, it throws StackOverflowError.
  6. If the error is uncaught on the main thread, the application may stop; if it happens on a worker thread, that thread usually dies and the request fails.

Why it happens

The classic cause is infinite recursion, such as a method that calls itself without a correct base case. A base case is the stopping condition in a recursive algorithm. It can also happen with mutual recursion, where method A calls B and B calls A forever, or with a legitimate algorithm that just goes too deep for the current stack size.

TopicStackOverflowErrorOutOfMemoryError
Memory areaThread stackHeap or native memory
Typical causeDeep recursionToo many objects or threads
Can catch?Usually not for recoveryUsually not for recovery
FixStop recursionReduce allocation

For performance thinking, recursion usually uses O(depth) extra stack space, while an iterative version often uses O(1) stack space. That matters because a stack frame is small but not free: if one frame is roughly 100-200 bytes, a 1 MB stack can overflow after only a few thousand to ten thousand calls. Changing -Xss to a larger value can delay the failure, but it is only a band-aid if the algorithm is unbounded.

Important edge cases

  • Large local variables and deep call chains make the stack frame bigger, so overflow can happen sooner.
  • Java does not guarantee tail-call optimization, so you should not assume a tail-recursive method will be turned into a loop.
  • Trying to do heavy work after catching the error is risky because the thread is already in a bad state; at most, log a minimal message and fail fast.

Real-World Story: A marketplace app had a product-catalog service that built breadcrumbs by walking from a category to its parent category recursively. One bad data import created a cycle: Shoes -> Sale -> Clearance -> Shoes. The first request into that category made the method call itself forever, the thread hit StackOverflowError, and users saw 500 errors when opening product pages. The logs showed the same method repeated dozens of times in the stack trace, which was the clue that the code was not stopping at a root node.

The fix was twofold: validate the category graph on write, and add a visited-set plus a max-depth guard on read. Without that, the bug would come back the next time cyclical data slipped in.

Java
public class StackOverflowErrorDemo {
    private static long depthReached = 0;

    public static void main(String[] args) {
        System.out.println("Recursive sum of 5 = " + recursiveSum(5));
        System.out.println("Iterative sum of 5 = " + iterativeSum(5));

        try {
            induceOverflow(1);
        } catch (StackOverflowError error) {
            System.out.println("Caught StackOverflowError after about " + depthReached + " recursive calls.");
            System.out.println("This shows the call stack ran out of space.");
        }
    }

    // A correct recursive method needs a base case. Without it, the call stack keeps growing.
    private static long recursiveSum(long n) {
        if (n == 0) {
            return 0;
        }
        return n + recursiveSum(n - 1);
    }

    // Iteration uses one method frame, so it avoids growing the call stack for every step.
    private static long iterativeSum(long n) {
        long sum = 0;
        for (long i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }

    // Deliberately broken: no base case, so this keeps pushing frames until the JVM throws the error.
    private static void induceOverflow(long depth) {
        depthReached = depth;
        induceOverflow(depth + 1);
    }
}

Follow-up & Tricky Questions:

  • Follow-up: What usually causes StackOverflowError in Java? The most common cause is a recursive method with no correct base case. It can also come from mutual recursion, a recursive walk over a very deep tree, or accidental cycles in data.
  • Follow-up: Is it an Exception? No. It is an Error, more specifically a VirtualMachineError, so normal business-logic handling is not the main use case.
  • Follow-up: Can you catch it? Yes, you can catch StackOverflowError specifically, but you usually should not try to recover and continue doing complex work. The safe response is to log, stop the bad path, and fail fast.
  • Follow-up: How do you prevent it? Add a real base case, protect against cycles, limit recursion depth, or rewrite the algorithm iteratively. If the recursion is only for convenience, iteration is often the safer production choice.
  • Follow-up: Does -Xss solve it? No. It only changes the thread stack size, which may delay the crash but does not fix the underlying unbounded call pattern.
  • Tricky: Will catch (Exception e) handle it? No, because StackOverflowError does not extend Exception. You would need to catch StackOverflowError or Throwable, but using that as a recovery strategy is usually a bad idea.
  • Tricky: Can a simple loop cause it? Not by itself. A normal loop reuses the same stack frame; the overflow comes from repeated method nesting, recursion, or a hidden callback chain that keeps adding calls.
  • Tricky: Does Java optimize tail recursion? No guarantee. Some languages or runtimes may do that, but Java does not promise tail-call elimination, so you must not rely on it.

Common Mistakes:

  • Saying it is an Exception. Correction: it is an Error, which signals a serious JVM-level problem.
  • Assuming more heap memory will fix it. Correction: stack and heap are different areas; this problem is about the thread stack.
  • Using recursion without a real stopping condition. Correction: every recursive path must reach a base case.
  • Thinking -Xss is a fix. Correction: it only increases stack size; the algorithm still needs to be corrected.

Memory Hook: Picture a stack of plates: every method call adds one plate, and StackOverflowError happens when the pile hits the ceiling.

Cheat Sheet:

  • It means the thread ran out of call stack space.
  • Most often caused by infinite or very deep recursion.
  • It is an Error, not a normal Exception.
  • Each method call creates a stack frame for locals and return info.
  • Fix the code first; -Xss only changes the limit.

Practice Tasks:

  • Write a recursive factorial method with a correct base case, then change it to an infinite recursion and observe the failure.
  • Convert a recursive tree traversal into an iterative one using your own stack.
  • Add cycle detection to a parent-pointer traversal so it cannot loop forever.
Previous
Back to Questions←→to navigate
Next

Recommended Resources

Recommended Book

Cracking the Coding Interview

189 Programming Questions and Solutions

Recommended Book

Cracking the Coding Interview

189 Programming Questions and Solutions

public class StackOverflowErrorDemo { private static long depthReached = 0; public static void main(String[] args) { System.out.println("Recursive sum of 5 = " + recursiveSum(5)); System.out.println("Iterative sum of 5 = " + iterativeSum(5)); try { induceOverflow(1); } catch (StackOverflowError error) { System.out.println("Caught StackOverflowError after about " + depthReached + " recursive calls."); System.out.println("This shows the call stack ran out of space."); } } // A correct recursive method needs a base case. Without it, the call stack keeps growing. private static long recursiveSum(long n) { if (n == 0) { return 0; } return n + recursiveSum(n - 1); } // Iteration uses one method frame, so it avoids growing the call stack for every step. private static long iterativeSum(long n) { long sum = 0; for (long i = 1; i <= n; i++) { sum += i; } return sum; } // Deliberately broken: no base case, so this keeps pushing frames until the JVM throws the error. private static void induceOverflow(long depth) { depthReached = depth; induceOverflow(depth + 1); } }