Card 04/ 09
All 9 cards
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.
StringBuilder first = new StringBuilder("one");
StringBuilder second = new StringBuilder("two");
first = second;
System.out.println(first);twoLine 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.
| After | first reaches | second reaches | Unreachable |
|---|---|---|---|
| Line 2 | The "one" builder | The "two" builder | Nothing |
| Line 4 | The "two" builder | The "two" builder | The "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.