Senior
Tell me about stack memory (Stack) and heap (Heap) in Java
sobes.tech AI
Answer from AI
In Java, stack memory (Stack) and heap (Heap) are two main regions of memory with different purposes and characteristics.
Stack:
- Stores local variables of methods, parameters, and return addresses.
- Each thread has its own stack.
- Memory management is automatic: a stack frame is created when a method is called, and removed when it exits.
- Fast access, but limited size.
- Stores primitive types and references to objects in the heap.
Heap:
- Stores objects and arrays created via
new. - Shared among all threads.
- Memory management is handled by the garbage collector.
- The heap size is usually larger and dynamically adjusts.
- Objects in the heap live as long as there are references to them.
Example:
public void example() {
int a = 10; // 'a' is stored in the stack
MyObject obj = new MyObject(); // reference 'obj' in the stack, object in the heap
}
Thus, the stack manages method calls and local data, while the heap is responsible for dynamic storage of objects with longer lifetimes.