Heap vs Stack
Memory areas in JVM
Interview Relevant: Fundamental concept
6 min read
Heap vs Stack
The JVM divides memory mainly into Heap and Stack, each serving a distinct purpose.
- Heap: Stores objects, shared across threads
- Stack: Stores method calls, local variables, thread-specific
Interview Tip: Stack memory is faster and automatically freed, heap memory is GC-managed.
Code Examples
Stack vs Heap allocation
java
1
2public void test() {
3 int x = 10; // Stack
4 User u = new User(); // Reference in stack, object in heap
5}
6 Use Cases
- Understanding performance
- Debugging memory issues
Common Mistakes to Avoid
- Assuming objects are stored on stack
- Confusing reference vs object