Clean • Professional
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.
Key Features
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;
}
}
Key Features
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;
}
}
p is stored in stack, pointing to the Person object in heap.| 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 |