What is the difference between stack and heap memory in Java?
The stack stores method calls and local variables, and it is freed automatically when a method returns. The heap stores objects created with new, and it is managed by the garbage collector. The stack is fast and small with a last in first out order, while the heap is larger and holds objects that can live beyond a single method call.
- The stack stores method calls and local variables and is freed automatically when a method returns.
- The heap stores objects created with new and is managed by the garbage collector.
- Stack memory is fast but limited, while heap memory is larger but slower to allocate.
What lives on the stack
Each method call gets a stack frame that holds its local variables and the reference to the object. When the method ends, its frame is removed instantly. This is why local primitives are cheap and short lived.
What lives on the heap
Objects created with new live on the heap. A variable on the stack often just holds a reference that points to the object on the heap. The garbage collector reclaims heap objects once nothing points to them.
void demo() {
int x = 5; // x on the stack
String s = new String("hi"); // s reference on stack, object on heap
}
A clean summary is primitives and references on the stack, objects on the heap, stack freed automatically and heap cleaned by garbage collection. Mentioning that a stack variable can hold a reference to a heap object shows real understanding.
Frequently asked questions
Where are objects stored in Java?
Objects live on the heap, while the reference variable that points to an object lives on the stack if it is a local variable.
What causes a StackOverflowError?
It happens when the stack runs out of space, usually from very deep or infinite recursion that keeps adding method frames.
Common follow up questions
Related interview questions
Want the full Java guide?
Read every Java concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the Java guide All Java questions