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.
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.
StackOverflowError.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.
| Topic | StackOverflowError | OutOfMemoryError |
|---|---|---|
| Memory area | Thread stack | Heap or native memory |
| Typical cause | Deep recursion | Too many objects or threads |
| Can catch? | Usually not for recovery | Usually not for recovery |
| Fix | Stop recursion | Reduce 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.
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.
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:
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.Exception? No. It is an Error, more specifically a VirtualMachineError, so normal business-logic handling is not the main use case.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.-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.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.Common Mistakes:
Exception. Correction: it is an Error, which signals a serious JVM-level problem.-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:
Error, not a normal Exception.-Xss only changes the limit.Practice Tasks: