The Heap: Where Objects Live
What You'll Learn
You'll understand heap memory as the dedicated runtime area where Java stores all objects your program creates.
The Heap: Java's Object Storage Warehouse
When you use the new keyword to create an object, Java doesn't just conjure it out of thin air—it allocates space for that object in a special memory region called the heap.
Think of the heap as a giant warehouse where all objects live during your program's execution. Every time you write something like String name = new String("Alice") or int[] numbers = new int[5], Java reserves space in the heap to store that object or array.
Why the Heap?
The heap exists separately from the stack (where local primitive variables and references live) because objects can have longer, more complex lifetimes. Multiple reference variables might point to the same object on the heap, and objects can outlive the method that created them.
The heap is shared across all threads in your program, meaning any part of your code can access heap objects if it has a reference to them.
What Lives on the Heap?
- All objects created with
new - All arrays (even primitive arrays like
int[]) - String objects
- Wrapper class instances (
Integer,Double, etc.)
Reference variables themselves live on the stack, but they point to objects that live on the heap.
Memory Management
Java's garbage collector automatically reclaims heap memory when objects are no longer referenced, so you don't manually delete objects like in some other languages.
Key Takeaway: The heap is Java's centralized memory region where all objects and arrays are allocated and stored at runtime, managed automatically by the garbage collector.