Visualizing garbage collection

It can be helpful to visualize how garbage collection works and, perhaps more importantly, the need for it. Consider the following code snippet that progressively creates the string Garbage:

    001 String var = new String("G");    002 var += "a";    003 var += "r";    004 var += "b";    005 var += "a";    006 var += "g";    007 var += "e";    008 System.out.println("Your completed String     is: " + var + ".");

Clearly, the preceding code generates the output provided as follows:

    Your completed String is Garbage.

What might not be clear is that the sample code results in five unreferenced string objects. This is due, in part, because strings are immutable. As you can see in the following illustration, with each successive line of code, ...

Get Java 9: Building Robust Modular Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.