StackOverflowError vs OutOfMemoryError in Java
Fast recall
Quick revision
Core answer
Whether you understand JVM memory areas (stack vs heap), what causes each error, and how to diagnose them in production
Thinking StackOverflowError is related to heap memory, or trying to catch and recover from OutOfMemoryError in a catch block
Explain the different subtypes of OOM (heap space, metaspace, GC overhead limit, unable to create native thread), mention -Xss for stack size tuning, and describe how to diagnose each with heap dumps and thread dumps
Interview-ready guide
Interview answer
StackOverflowError and OutOfMemoryError are Java's two most common JVM-level fatal errors — they affect completely different memory regions, have different root causes, and require entirely different diagnosis approaches.
StackOverflowError:
- A single thread's call stack runs out of space — almost always from infinite or very deep recursion
- Stack trace shows the recursive method directly — straightforward to diagnose
- Fix: add a base case or convert to iteration; increasing
-Xssrarely helps
OutOfMemoryError subtypes:
- "Java heap space": GC can't free enough memory — either a leak (post-GC live set grows over time) or undersized heap (post-GC live set stable)
- "Metaspace": classloader leak — common during hot redeployment in app servers
- "GC overhead limit exceeded": JVM spends 98% of time collecting less than 2% — effectively a leak under pressure
- "unable to create native thread": unbounded thread creation exhausted OS thread limits
Both extend Error:
- Signals the JVM is in a state you generally cannot safely recover from — don't
catchand continue
I recommend setting -XX:+HeapDumpOnOutOfMemoryError in every production deployment — the snapshot is essential for root cause analysis and you don't want to scramble to reproduce after a container restart.
StackOverflowError vs OutOfMemoryError in Java
Direct Answer
StackOverflowError — thread stack exhausted (usually unbounded recursion). OutOfMemoryError — heap (or metaspace/direct) cannot satisfy allocation. Different regions, different fixes.
Common Mistakes & Pitfalls
Thinking StackOverflowError is related to heap memory, or trying to catch and recover from OutOfMemoryError in a catch block
Check your understanding
Answer these without looking back at the article.
- How do you configure -XX:+HeapDumpOnOutOfMemoryError?
- Can you recover from an OutOfMemoryError?
- What is the default stack size in Java and when would you change it?
Related interview prep categories
2Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.