Heap
The Heap is the memory area where all Java objects are actually stored, whenever you use the new keyword to create them. Unlike the Stack, the Heap is shared across all threads in a program.
1. What is the Heap (in JVM memory)?
The Heap is the memory area where all Java objects are actually stored, whenever you use the new keyword to create them. Unlike the Stack, the Heap is shared across all threads in a program.
2. Why is it used?
Objects generally need to exist beyond the lifetime of a single method call — they may be passed around, stored, and used across many different parts of a program. The Heap provides this more flexible, longer-lived storage.
3. Real-Life Example
Think of a shared warehouse where all finished products from different departments are stored together, accessible by multiple departments as needed, rather than each department keeping products only in their own private desk drawer.
4. Syntax
javaClassName obj = new ClassName(); // 'obj' reference is on Stack, actual object is in Heap
5. Example Program
javaclass Student { String name; } public class HeapDemo { public static void main(String[] args) { Student s = new Student(); // object created in Heap s.name = "Priya"; System.out.println(s.name); } }
Output:
Priya6. Key Points to Remember
- All objects created with
neware stored in the Heap, regardless of which method created them. - The Heap is shared across all threads, unlike the Stack, which is separate for each thread.
- The Heap is managed by the Garbage Collector, which automatically removes objects no longer in use.