Where do objects live in the JVM, and what lives on the stack?
Options
- Objects on the stack; local primitives on the heap
- Objects on the heap; each thread's stack holds locals and calls (Correct option)
- Everything lives on the heap, including method calls
- Everything lives on the stack, including all objects
Answer
Objects on the heap; each thread's stack holds local variables and method calls
Why
The heap is the big shared memory area where all objects are created (new). The garbage collector cleans it.
Each thread has its own stack: a small area where each method call gets a frame with its local variables (primitives and references to objects). When the method returns, the frame is removed automatically.
A StackOverflowError means too many nested calls (usually infinite recursion); OutOfMemoryError means the heap is full.
Remember
Heap = objects (shared). Stack = method frames (per thread).