What is the difference between stack and heap? When do StackOverflowError and OutOfMemoryError occur?
Short answer
Each thread has its own stack holding the local variables of the running method, cleared when the method ends. The heap is shared, holds every object, and is cleaned by the GC (garbage collector).
3 points to say:
- Local variables live on the stack, objects on the heap.
- Recursion too deep:
StackOverflowError. - Heap full of still-referenced objects:
OutOfMemoryError.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.