What is the difference between stack and heap memory in Java?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Java topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
The stack stores method call frames — each thread has its own stack. Local variables, method parameters, and return addresses are stored here. Stack memory is automatically managed (LIFO) and is very fast. Objects cannot be stored on the stack (only references to objects). The heap is shared among all threads and is where all objects and their instance fields are allocated. It is managed by the garbage collector. Heap access is slower than stack. A StackOverflowError occurs when the stack runs out of space (usually from infinite recursion). An OutOfMemoryError occurs when the heap is full and GC cannot free enough memory.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.