Difficulty: Intermediate
Explain the JVM memory areas: heap, stack, metaspace and others. What causes StackOverflowError vs OutOfMemoryError?
Understanding JVM memory turns you from someone who writes Java into someone who can debug it at 2 AM when production is out of memory. Interviewers love this topic because it separates memorizers from engineers. Let me lay out the map.
The heap is the big shared area where all objects and arrays are allocated. It is created at JVM start, shared by all threads, and managed by the garbage collector. It is typically divided into a young generation (Eden plus two survivor spaces) and an old generation (tenured). New objects start in Eden. Surviving objects get promoted after a few collections. The heap size is controlled with -Xms (initial) and -Xmx (maximum). The String pool also lives here since Java 7. If the heap fills and GC cannot free enough, you get OutOfMemoryError: Java heap space.
The stack is per thread. Each thread gets its own stack when it starts, sized with -Xss. Each method call pushes a frame containing local variables, the operand stack and a reference to the runtime constant pool. When the method returns, its frame is popped. Primitive locals are stored directly in the frame; for objects, the frame stores only the reference, while the object itself lives on the heap. Stack memory is automatically freed on return, needs no GC, and is inherently thread-safe since no one else can touch your locals. Infinite or very deep recursion exhausts it and throws StackOverflowError.
Metaspace replaced PermGen in Java 8. It stores class metadata: class structures, method bytecode, constant pools and static-related metadata. Unlike PermGen, it lives in native memory, not the heap, and grows dynamically by default until the OS limit unless capped with -XX:MaxMetaspaceSize. You see OutOfMemoryError: Metaspace mainly with class loader leaks, for example redeploying web apps repeatedly or generating tons of classes dynamically with proxies or bytecode libraries. Note that static variable values themselves are stored in the heap (in the Class object) in modern JVMs.
Other areas: the PC register per thread holds the address of the current instruction. The native method stack supports JNI calls. The code cache stores JIT-compiled native code. Direct buffers use off-heap memory too.
Common trick questions. Where is an object stored if it is declared inside a method? On the heap; only the reference is on the stack, although the JIT can use escape analysis to allocate non-escaping objects on the stack or eliminate them entirely. Where do instance variables live? Inside the object, on the heap. Are static variables on the stack? No. Is Java pass-by-value? Yes, always: for objects, the reference is copied, so you can mutate the object through the copy, but reassigning the parameter does not affect the caller.
Difference between the two errors: StackOverflowError is about depth of calls in one thread, fixed by correcting recursion or increasing -Xss. OutOfMemoryError is about total memory, fixed by finding leaks with a heap dump (jmap or -XX:+HeapDumpOnOutOfMemoryError) and tools like VisualVM or Eclipse MAT, or by tuning -Xmx.
A useful sentence to close with: the stack is fast, small and automatic; the heap is large, shared and garbage collected.
public class MemoryDemo {
static int depth = 0;
static void recurse() {
depth++;
recurse();
}
static void change(int[] arr) {
arr[0] = 99;
arr = new int[] {5};
}
public static void main(String[] args) {
try {
recurse();
} catch (StackOverflowError e) {
System.out.println("Stack overflow caught: " + (depth > 1000));
}
int[] a = {1, 2};
change(a);
System.out.println(a[0]);
}
}
Each recursive call adds a frame until the thread stack is full. The array lives on the heap, so the mutation through the copied reference is visible to the caller, but reassigning the local parameter is not.
Heap, Stack, Metaspace, StackOverflowError, OutOfMemoryError