First, to answer your question "Can String objects be GCed?": Yes, String objects are just like any other kinds of objects and they are garbage collected just like other kinds of objects.
Note that there is only one String object in that piece of code, and that's the String object that represents the string literal "abc". The variable
str refers to that String object.
Java has a special optimization for strings: the string pool. For string literals, such as "abc" in your code, a String object is created and placed in a pool. When you use "abc" multiple times in your program, the same String object in the pool is used; Java does not create more than one String object with the content "abc". This saves memory.
So when the variable
str goes out of scope, the String object that it points to will not be garbage collected - it will remain in the string pool.
Note that the string pool is normally only used for string
literals. Other String objects, that do not come from String literals, are not maintained in the pool, and will be garbage collected normally. (Well, you can explicitly make a String go into the string pool by calling intern() on it, but you would not normally do that in a Java program).
[ December 16, 2007: Message edited by: Jesper Young ]