Stack & Heap Memory in Java
In Java, understanding Stack and Heap memory is crucial for writing efficient programs. Both are part of the JVM memory structure, but they store and manage data differently.
Stack Memory
- The Stack is a thread-specific memory area that stores method calls, local variables, and references.
- It works on a LIFO (Last In, First Out) principle.
Key Features
- Stores primitive local variables and references to objects in Heap.
- Each thread has its own stack.
- Memory is automatically freed when a method call ends.
- Faster access due to contiguous memory allocation.
- Limited in size — excessive recursion may cause StackOverflowError.
Example
public class StackExample {
public static void main(String[] args) {
int a = 10; // Stored in stack
int b = 20; // Stored in stack
int result = sum(a, b);
System.out.println(result);
}
static int sum(int x, int y) {
int result = x + y; // Stored in stack
return result;
}
}
- Each method call creates a stack frame.
- Stack memory is cleared when the method finishes execution.
Heap Memory
- The Heap is a shared memory area where objects and instance variables are stored.
- It is managed by the Garbage Collector (GC).
Key Features
- Stores all objects, arrays, and instance variables.
- Accessible by all threads.
- Objects remain in Heap until GC removes unused objects.
- Slower than Stack due to dynamic memory allocation.
- Usually larger than Stack memory.
Example
public class HeapExample {
public static void main(String[] args) {
Person p = new Person("Alice"); // Object stored in heap
}
}
class Person {
String name; // Instance variable stored in heap
Person(String name) {
this.name = name;
}
}
- Reference variable
pis stored in stack, pointing to the Person object in heap.
Stack vs Heap: Quick Comparison
| Feature | Stack | Heap |
|---|---|---|
| Memory Type | Per-thread | Shared among threads |
| Stores | Local variables, method calls | Objects, instance variables |
| Memory Management | Automatic (LIFO) | Managed by Garbage Collector |
| Access Speed | Fast | Slower |
| Size | Limited | Larger |
| Lifetime | Ends with method execution | Until GC removes objects |
| Overflow Risk | StackOverflowError | Memory leaks if objects are not dereferenced |
Best Practices
- Use stack for local variables and short-lived data.
- Use heap for objects that need to persist beyond a method.
- Avoid memory leaks by nullifying unused references.
- Be cautious of deep recursion to prevent stack overflow.
Points to Remember :
- Stack memory: fast, short-lived, per-thread, stores local variables and method frames.
- Heap memory: slower, long-lived, shared, stores objects and instance variables.
