Card 02/ 09

ExampleDifficulty: Intermediate1 min

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:

java
void process() {
    int count = 3;
    String label = "total";
    List<String> rows = new ArrayList<>();
    rows.add(label);
}
Where each thing in the method lives
ThingLivesGone when
count, holding 3The stack frameprocess() returns
label, holding an addressThe stack frameprocess() returns
The string "total"The heap, in the pooled areaEffectively never, while the class is loaded
rows, holding an addressThe stack frameprocess() returns
The ArrayList objectThe heapNothing 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.