Stack vs Heap: References and Objects
What you'll learn: How local variables (references) and the actual objects they point to live in different memory regions.
When you declare a reference variable inside a method, something interesting happens: the variable itself and the object it points to live in completely different places in memory.
The Split Storage Model
Think of the stack as a bulletin board where you pin notes, and the heap as a warehouse where you store boxes. When you write:
String name = new String("Alice");
Two things happen:
- The variable
nameis created on the stack (like pinning a note to the bulletin board) - The actual
Stringobject"Alice"is created on the heap (like storing a box in the warehouse) - The value stored in
nameis a reference — essentially the address of where that object lives on the heap (like writing "aisle 5, shelf 3" on your note)
Why This Matters
Local variables live on the stack because they're temporary — they disappear when the method finishes executing. But objects live on the heap because they can outlive the method that created them. Multiple references (possibly from different methods or parts of your program) can point to the same heap object.
public void example() {
String s1 = new String("Hello"); // s1 lives on stack, points to heap
String s2 = s1; // s2 also lives on stack, points to same heap object
}
Both s1 and s2 are stack variables holding references to the same heap object.
Key Takeaway: Local reference variables live on the stack and hold memory addresses pointing to objects that live on the heap—the reference and the object are stored separately.