On pg 429 in the Sierra/Bates Study Guide for Java 6 cert (diagram):
Step 1: shows the ref var "s" being stored on the heap as "abc"---got it
Step 2: indicates both ref vars, s2 and s refer to the same object on the heap ("abc")--got it
Step 3: indicates s2 refers to the "abc" object on the heap and s is a deleted ref to "abc" and "abcdef".
Step 3 is where I am running into trouble. If "def" as never assigned a ref variable, then why does it say that s is a deleted ref to "abcdef"? I am understanding the purpose of the appending of ("def") in this example is only creating the object and not assigning a reference. TIA
Ok, let me just state the way I understand this and tell me where I'm wrong:
the string literal ("def"), as it is displayed, creates an object but has no reference variable that can refer to it. In other words, how can the reference be deleted for "abcdef" if "def" reference was never created...why concatenate something for a reference variable that no longer exists?
Brings up another question:
Sooo, if "def" is not on the heap is in then in the stack as an object? and would this make it available for garbage collection if it is never referenced?
Strings live in a very special place called the String pool.
Oh, your "def" exists. It's a literal floating around in the pool somewhere. There is no reference to it, but it's swimming around in the pool. String literals in the pool are not garbage collected, even if there is no reference to them. If you create a new reference to a def:
That String in the pool gets a new reference.
HOWEVER, using the constructor actually creates a new String:
You should never do this.... allow the JVM to keep track of Strings for you.
When you do things right, people won't be sure you've done anything at all.
Actually, "abcdef" won't be in the String pool, because it never was a String literal. It's also not lost, because it is referenced by s2.
"def" on the other hand, has no more references to it in your code, but it's not lost, because it's referenced by the String pool.
It will help if you understand that the String pool is no special magical place. It's simply a static list of Strings maintained by the String class. String literals in your code will be added to it automatically when your program starts.
This is my fault...what happens when you study way too long. I overlooked the fact that the concatenation in step 3 was indeed assigned to s. That is why I kept questioning how the concatenation could actually succeed.
Sorry for the blunder, but thanks so much for the help!
I don't like that guy. The tiny ad agrees with me.