Card 01/ 09
All 9 cards
ConceptDifficulty: Intermediate1 min
Where a Value Lives While Your Method Runs
Two failures that look alike from the outside: a program that dies after four seconds of recursion, and one that dies after four hours of steady work. They exhaust different things, and telling them apart starts with knowing there are two.
The Java Virtual Machine — the JVM — divides the memory it uses into two regions with different rules.
| Compared on | The stack | The heap |
|---|---|---|
| Holds | One frame per method call | Every object created with new |
| A frame holds | Parameters, local variables, the return address | — |
| Cleared | When the method returns | By the garbage collector, when nothing can reach it |
| Per thread | One stack each | Shared by all threads |
| Size | Fixed, small | Configurable, large |
Every object is on the heap, without exception. A local variable holding a List sits in the stack frame; the list itself is on the heap, and the variable holds its address.
So a local int disappears the moment its method returns, and an object outlives the method that made it for as long as anything still points at it. That difference is what the rest of this topic is about.