Why this matters
StackOverflowErrorandOutOfMemoryErrorare both memory failures, and the one you get tells you exactly which region filled up.- Thread safety only exists as a concern because stacks are private and the heap is shared.
- Every later topic — garbage collection, memory leaks, escape analysis — assumes you can place a given value in the right region.
The two regions
Stack — per thread
main() frameuser → reference
greet() framecount = 3 (primitive)
Popped the moment a method returns.
Heap — shared
User objectname = "Asha"
String object"Asha"
Cleared by the garbage collector, not by returning.
| Aspect | Stack | Heap |
|---|---|---|
| Holds | Method frames: locals, parameters, references, return address | Every object and array, plus their instance fields |
| Shared | One private stack per thread | One heap shared by all threads |
| Allocation | Push a frame on call, pop on return | Allocated by new, reclaimed by the collector |
| Size | Small — around 512 KB to 1 MB per thread | Large — hundreds of megabytes to gigabytes |
| Lifetime | Exactly the duration of the method call | Until no reference can reach the object |
| Speed | Very fast — a pointer bump | Slower, and subject to collection pauses |
| When exhausted | StackOverflowError | OutOfMemoryError |
Holds
StackMethod frames: locals, parameters, references, return addressHeapEvery object and array, plus their instance fieldsShared
StackOne private stack per threadHeapOne heap shared by all threadsAllocation
StackPush a frame on call, pop on returnHeapAllocated by new, reclaimed by the collectorSize
StackSmall — around 512 KB to 1 MB per threadHeapLarge — hundreds of megabytes to gigabytesLifetime
StackExactly the duration of the method callHeapUntil no reference can reach the objectSpeed
StackVery fast — a pointer bumpHeapSlower, and subject to collection pausesWhen exhausted
StackStackOverflowErrorHeapOutOfMemoryError
Private and automatic versus shared and collected. Those two differences explain everything else.
Placing a value
Loading compiler…
The rule, stated precisely
- A primitive local stores its value directly in the frame.
- A reference local stores an address in the frame; the object it names is on the heap.
- Instance fields live inside the heap object, whatever their type — an
intfield is on the heap. - Static fields live with the class, in metaspace, and are reachable from every thread.
- The frame disappears the moment the method returns. The objects it referenced survive if anything else still reaches them.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 5 sections
- Frames and the call chain
- Why thread safety exists
- Escape analysis
- Reading the two errors
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.