Okay, let me try to explain how this works. Keep in mind, though, that garbage collection of String objects
is not on the exam. Therefore, this discussion is informative only and won't be required for the exam.
Here's the first program mentioned:
So, when this code finishes execution, how many objects are available for garbage collection? The answer is 0. No objects are eligible for garbage collection. The reason for this is that every String literal has a reference stored in the String Literal Pool. As that reference is never cleared, each object always has an active reference to it and is not eligible for garbage collection. If you don't understand the String Literal Pool, I'd suggest reading (or re-reading) my article,
Strings, Literally.
Now, let's take a look at the second program:
In this situation, there is an object available for garbage collection when the code complete, but there are 3 String objects, is all. The literals, "String1" and "String2", are referenced from the String Literal Pool - these objects will never be available for garbage collection.
However, by using the keyword "new" in the second line, you create a third String object which is equivalent to a String already created and referenced from the String Literal Pool. Note that, while these two String objects are equivalent (contain the same value), they are not the same object. They are two distinct String objects.
As this new object has no reference to it from the String Literal Pool, when the last line executes, setting the reference variable "two" to null, there is no longer a reference to that String and it is eligible for garbage collection.
I hope that helps,
Corey