Card 02/ 09

ExampleDifficulty: Intermediate1 min

One Method, Two Regions

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

Three of the five are variables, and all three vanish together when the frame is discarded. Neither of the two objects vanishes at that moment — they become unreachable, which is a different thing and happens first.

What to notice: nothing in the method decided when the list would be freed. The frame going away only removed the last thing pointing at it.