Junior
What is the difference between Stack and Heap?
sobes.tech AI
Answer from AI
Stack and Heap are two memory areas used by the Java Virtual Machine (JVM) to store data.
Main differences:
| Characteristic | Stack | Heap |
|---|---|---|
| Purpose | Storage of primitive data types and object references | Storage of objects |
| Size | Fixed for each thread | Dynamic, shared among all threads |
| Management | LIFO (Last-In, First-Out), managed by JVM | Garbage Collector |
| Speed | Faster | Slower |
| Thread | Belongs to a specific thread | Shared among all threads |
| Lifecycle | Tied to the method’s lifecycle | Determined by Reachability |
Example usage:
// Primitive data type stored in Stack
int count = 10;
// Object stored in Heap
String name = new String("Java");
// Reference to the object name stored in Stack
String anotherName = name;
Stack:
- Variables of primitive types (int, boolean, float, etc.) store their values directly in the Stack.
- References to objects (e.g.,
nameandanotherNamein the example) store in the Stack the address where the object itself is located in the Heap. - The size of the Stack is fixed for each thread. StackOverflowError occurs in case of too deep recursion or creating a large number of local variables.
- Access to data in the Stack is organized on a LIFO basis. When a method finishes execution, its data is automatically removed from the Stack.
Heap:
- All objects created with the
newoperator are located in the Heap. - The Heap is a shared memory area for all threads within a JVM.
- The size of the Heap can change dynamically.
- Memory management in the Heap is automatic, handled by the garbage collector. Unused objects (those with no active references) are removed from the Heap, freeing memory. OutOfMemoryError occurs when there is not enough memory in the Heap to create new objects.