A String Question to Ponder
Posted on 2002-06-07
Ok. Experts, try this one....
I have a String Constant.
String str1 = "Hey baby!";
So, what happens here is that there is a String in a memory location (say at Address 5000) and str1 is now pointing (Referring) to that address (meaning str1 has value 5000).
If I do a change to this string....
str1 = "Hello Baby!";
now str1 is NOT pointing to the same address. i.e.str1 contains no 5000 but something else. i.e. "Hello Baby!" is a new string constant. In fact the original string "Hey Baby!" is now garbage collected by the gc.
Now if I allocate a string like this...
String str2 = new String("Hey baby!");
Then a new memory location (an object) is created and the value "Hey Baby!" is placed in there. So str2 is now referring to a memory location say 8000). THIS NOT A STRING CONSTANT. THIS IS A STRING OBJECT according many books. If I do a change to this string...
str2 = "Hello Baby!";
Then the same thing happened in str1 also happens here. In other words, the String Object str1 is now garbaged collected and str2 is now pointing to a new String object with the value "Hello Baby!".
So in both cases exact same result happens. If that is the case what's the use of having a String Constant?. Isn't a String object acts exactly as a String Constant?