Stack vs Heap in Java
1. Stack Memory
- Used for storing method calls and local variables.
- Follows LIFO (Last-In-First-Out).
- Each thread has its own stack.
- Very fast memory allocation and deallocation.
- Automatically cleared when method finishes.
Example:
int a = 5; // 'a' stored in stack
Method calls push a new stack frame, removed on return.
2. Heap Memory
- Used for storing objects created with 'new'.
- Shared among all threads.
- Slower access compared to stack.
- Managed by Garbage Collector.
- Used for large and long-lived data.
Example:
Person p = new Person(); // Object in heap, 'p' in stack
3. Summary Table
Feature | Stack | Heap
------------------|-----------------------|-----------------------------
Scope | Method local | Global to app (shared)
Stack vs Heap in Java
Speed | Fast | Slower
Garbage Collected | No | Yes
Thread Safety | Yes | No (needs sync)
Stores | Primitives, refs | Objects, arrays
4. Real-world Analogy
- Stack is like your kitchen counter: temporary workspace, cleared often.
- Heap is like your fridge/pantry: long-term storage, shared by everyone.
Example: Car car = new Car();
- 'car' reference is on the stack
- Car object itself is on the heap