Lesson 32: Java Memory Model: Stack vs Heap

02 Aug 2026 1 min Swarnil Singhai

Local variables and method calls live on the stack; objects live on the heap — understanding this explains performance and garbage collection.

Real-time example

A recursive function that goes too deep throws StackOverflowError — the stack has a small fixed size per thread, unlike the heap.

void recurse(int depth) {
    System.out.println("depth: " + depth);
    recurse(depth + 1); // eventually: StackOverflowError
}
// Objects created with new live on the heap and are
// reclaimed by the garbage collector once unreachable.

What's happening

Each method call pushes a stack frame holding local variables; when the method returns, the frame is popped — automatic and fast.

Deep unbounded recursion is a real production bug source — prefer iteration or increase -Xss deliberately, not by accident.

Advertisement