The Stack and the Heap: Where Variables Live
What You'll Learn
You'll understand the two different memory regions Java uses to store variables, and why primitives and objects live in different places.
Two Memory Regions
When your Java program runs, it uses two distinct areas of memory:
- The Stack: A fast, organized region for method calls and local primitive variables
- The Heap: A larger, flexible region where objects are stored
Think of the stack like a stack of cafeteria trays—orderly, fast to add and remove from the top. The heap is more like a storage warehouse—spacious but requires more effort to manage.
Where Primitives Live
When you declare a primitive variable (int, double, boolean, etc.), it lives directly on the stack:
int age = 25; // The value 25 lives on the stack
double price = 9.99; // The value 9.99 lives on the stack
The variable name and its value are stored together in the method's stack frame. When the method ends, these variables vanish instantly.
Where Objects Live
When you create an object with new, the object itself lives on the heap, but the reference variable lives on the stack:
int[] numbers = new int[5]; // The array object is on the heap
// The variable 'numbers' (a reference) is on the stack
The stack holds the "address" pointing to where the actual array lives on the heap. The heap stores the array's data.
Why This Matters
This separation explains key behaviors you've seen: primitives are copied by value, while reference types share the same object. Understanding stack vs heap is foundational to grasping how Java manages memory.
Key Takeaway: Primitive values live directly on the stack, while objects are allocated on the heap with only their references stored on the stack.