Card 04/ 09

ExampleDifficulty: Intermediate1 min

An Object Nothing Can Reach Any More

Four lines, and after the third one of the two objects created is already eligible for collection.

java
StringBuilder first = new StringBuilder("one");
StringBuilder second = new StringBuilder("two");

first = second;

System.out.println(first);
text
two

Line 4 pointed first at the second builder. Nothing else was holding the first one, so after that line there is no path from any root to it, and the collector may take it whenever it next looks.

What each variable reaches after line 4
Afterfirst reachessecond reachesUnreachable
Line 2The "one" builderThe "two" builderNothing
Line 4The "two" builderThe "two" builderThe "one" builder

Nothing was deleted, and no method was called to release anything. The object became garbage because the last reference moved, which is the only way anything ever becomes garbage.