Interview Q&A / Java

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the difference between OutOfMemoryError and StackOverflowError?

SHORT ANSWER

StackOverflowError happens when a thread call stack is exhausted, usually by endless recursion. OutOfMemoryError happens when the heap, or another memory area, cannot supply memory even after garbage collection.

Explain it simply

A stack of plates in a canteen: pile too many on one spot and it topples (StackOverflowError). A godown that is completely full of boxes, with no space for even one more, is OutOfMemoryError.

Example

java
static int depth(int n) {
    return depth(n + 1);        // no base case: StackOverflowError
}

static void leak() {
    java.util.List<byte[]> list = new java.util.ArrayList<>();
    while (true) {
        list.add(new byte[10_000_000]);   // keeps everything reachable: OutOfMemoryError
    }
}

What to say in the interview

"Both are Errors, not Exceptions. StackOverflowError is about the per-thread stack and is almost always an infinite or very deep recursion; the fix is a base case or an iterative approach, and -Xss changes the stack size. OutOfMemoryError: Java heap space means live objects fill the heap; it can also say Metaspace or unable to create native thread. I use a heap dump and a tool like Eclipse MAT to find what is holding memory, and increase -Xmx only after confirming it is not a leak."

Common mistakes

  • Raising -Xmx as the first response to an OutOfMemoryError caused by a leak.

#java#jvm#errors

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.