What is the difference between heap and stack memory in Java?
The stack holds method call frames with local primitives and references, and each thread has its own. The heap holds all objects and is shared by every thread and cleaned by the garbage collector.
Explain it simply
The stack is your study desk: it holds only what you are working on right now, and when you finish a task you clear it instantly. The heap is the big storage room of the college: everything is kept there, many people can reach it, and a caretaker (the garbage collector) removes things nobody uses.
Example
class Student {
String name;
Student(String name) { this.name = name; }
}
static void enroll() {
int seats = 60; // stack: primitive local variable
Student s = new Student("Asha"); // 's' (reference) on stack, object on heap
} // frame popped: 'seats' and 's' vanish
// the Student becomes garbage if nothing else points to itWhat to say in the interview
"Each thread gets its own stack, made of frames, one per method call. A frame holds local primitives and references. The heap is one area shared by all threads and holds every object and array. Stack memory is released automatically as methods return and is very fast; heap memory is released by the garbage collector. Too many nested calls cause StackOverflowError; too many live objects cause OutOfMemoryError. Because the heap is shared, objects there need thread-safety care."
Common mistakes
- Saying local objects live on the stack. The reference is on the stack; the object is on the heap (the JIT may optimise this, but the model stays the same).