Card 01/ 09

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.

The two regions, what lives in each, and what clears them
Compared onThe stackThe heap
HoldsOne frame per method callEvery object created with new
A frame holdsParameters, local variables, the return address—
ClearedWhen the method returnsBy the garbage collector, when nothing can reach it
Per threadOne stack eachShared by all threads
SizeFixed, smallConfigurable, 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.