What is the difference between stack and heap memory in Java?

7 minbeginnerstackheapmemory

Quick Answer

Each thread has its own stack, which stores local variables, method parameters, and primitive values in per-method call frames, following strict LIFO order and automatically reclaimed when a method returns. The heap is a single shared area (across all threads) where all objects and arrays are allocated, managed by the garbage collector rather than 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, and automatically reclaimed the instant the method returns, no GC involved. A stack has a fixed maximum size; exceeding it (typically via runaway/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]), regardless of which thread or method created it. Objects live on the heap until the garbage collector determines 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 (simple pointer bump, great cache locality, no synchronization needed since it's thread-private) but 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 deep/infinite recursion) throws StackOverflowError — a common early interview distinction.