What is the difference between stack and heap memory in Java?
Quick Answer
Each thread has its own stack, which stores local variables, method parameters, and primitive values in per-method call frames. It follows strict LIFO order and is reclaimed automatically when a method returns. The heap is a single shared area, across all threads, where all objects and arrays are allocated. It's managed by the garbage collector instead of being tied to any method's call frame.
Detailed Answer
Stack: each thread gets its own stack, made up of frames — one per active method call. A frame holds that method's local variables, parameters, and (for primitives) their actual values, plus references to heap objects. Frames are pushed on method entry and popped on return, strictly LIFO. They're reclaimed the instant the method returns — no GC involved. A stack has a fixed maximum size. Exceeding it, typically via runaway or infinite recursion, throws StackOverflowError.
Heap: a single memory area shared by all threads, where every object and array is allocated (new SomeClass(), new int[10]), no matter which thread or method created it. Objects live on the heap until the garbage collector decides they're unreachable and reclaims them. There's no deterministic "this method ended, free it now" moment like the stack has.
void method() {
int x = 5; // x itself lives on this call's stack frame
Point p = new Point(1,2); // the Point object lives on the heap;
// `p` (the reference/pointer to it) lives on the stack
}
Practical implications: stack access is very fast — a simple pointer bump, great cache locality, no synchronization needed since it's thread-private. But it's limited in size and lifetime. Heap access is slightly slower and subject to GC pauses, but objects can outlive the method that created them and be shared across threads.
Running out of heap space throws OutOfMemoryError: Java heap space. Running out of stack space, typically from deep or infinite recursion, throws StackOverflowError — a common early interview distinction.