Java Memory Model
Heap vs Stack
Understand where objects live, stack allocation, thread stack frames, and dynamic allocations.
Interview: Commonly tested on heap vs stack variable allocation, parameter passing, object reference locations, and StackOverflowError vs OutOfMemoryError.
In the JVM, memory is divided into runtime data areas. The two most critical areas for executing method calls and allocating objects are the Stack and the Heap.
Core Idea
Stack memory is thread-private, storing local variables and frames. Heap memory is shared, storing all objects.
Why It Matters
Understanding allocation prevents memory bloat and helps debug StackOverflowErrors in recursive pipelines.
Interview Lens
Tests tracing where references are stored vs. where the actual objects they point to reside in memory.
Memory Allocation Rules
- Stack Memory: Each thread gets its own private Stack. Methods are allocated Stack Frames containing primitive local variables and object reference handles. Access is LIFO (Last-In-First-Out) and extremely fast.
- Heap Memory: All objects created via the
newkeyword reside on the Heap. The Heap is globally shared among all threads. It is managed by automatic Garbage Collection (GC). - Variables: An instance variable of primitive type resides on the heap inside the object. A local reference variable resides on the stack, but points to an object on the heap.
Code Walkthrough
The following example maps how references on the stack point to object allocations on the heap.
public class MemoryLayoutDemo { public static void main(String[] args) { int localPrimitive = 10; // Stored in main() Stack framePoint point = new Point(5, 7); // Reference "point" on Stack; "new Point" on Heap
processPoint(point); }
private static void processPoint(Point p) { // "p" is a copy of reference on processPoint() Stack frame, pointing to same Heap object int val = p.x; } }
class Point { int x; // Stored on Heap as part of Point object int y;
Point(int x, int y) { this.x = x; this.y = y; } }
Interview-Relevant Information
Q: How do StackOverflowError and OutOfMemoryError differ?
Answer: A StackOverflowError occurs when a thread's stack runs out of memory, usually due to infinite recursion or excessively deep method call chains. An OutOfMemoryError (OOM) occurs when the JVM cannot allocate new objects on the Heap because it is full, and Garbage Collection cannot reclaim more space.
Quick Checklist
Where do object instances live? Where do local reference handles live? If yes, you understand Heap vs Stack.
Use Cases
Analyzing recursive algorithms to avoid stack overflow overhead.
Optimizing object creation frequency to decrease garbage collection pressure on the heap.
Common Mistakes
Assuming class member primitives reside on the stack (they reside on the heap as part of their enclosing object).
Thinking local variables are shared between threads (they are private to each thread's stack).