Card 02/ 09
Stack and Heap Example: One Method, Five Things, Two Regions
Four lines of a method, and where each variable and object actually sits.
Inside a method, local variables sit in the method's stack frame, the space set aside for that one call, and every object they refer to sits on the heap. Four lines, and each one puts something in a different place:
void process() {
int count = 3;
String label = "total";
List<String> rows = new ArrayList<>();
rows.add(label);
}| Thing | Lives | Gone when |
|---|---|---|
count, holding 3 | The stack frame | process() returns |
label, holding an address | The stack frame | process() returns |
The string "total" | The heap, in the pooled area | Effectively never, while the class is loaded |
rows, holding an address | The stack frame | process() returns |
The ArrayList object | The heap | Nothing can reach it any more |
The three variables vanish together when the frame is discarded. The list does not vanish at that moment: it becomes unreachable, which is a different thing, and the collector removes it later. The pooled string stays reachable, still referred to, from the pool.
Notice that nothing in the method decided when the list would be freed. The frame going away only removed the last thing pointing at it.
← → move through sections and cards