This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
I would say 5: 1� s1. 2� s2. 3� The string concatenation is not stored in s1 but it exists. 4� Same case for the s2 string concatenation. 5� The string you'll print is the concatenation s1, a blank and s2.
To verify this I created a little testprogram:
When you run this, you'll notice that: - s1 only gets concatenated with "winter " because of the statement s1 += "winter "; which is written out in full s1 = s1 + "winter "; thus resulting in modification of s1. - s2 is never modified.
Would it have been more correct if I had stated that the content of the object s1 was modified?
No. Think of "immutable" as meaning "read-only". If I write this:
What I've got is one reference (s1) which points to a String object. In line 1 the reference points the the value "initial string". In line two the value of the object doesn't change (becasue it can't), instead another String object is created with the value of "initial string more characters" and the reference s1 is pointed at that. The original String object still exists, its just no references point to it anymore.
Joined: Sep 15, 2004
Thanks Paul. So returning to the initial question, the result (number of String objects) then should be 6?
Remember that String objects are created for each of the literals in the code.
You are right that each of the literals in the code will be a string object but from that point of view the count should be 10 as in the last line , when s1 + " " it will create a new string object with s1 and blank in the last. Then again this object will be again concatnated with s2 creating another string object .
[ October 24, 2004: Message edited by: Rohan Kayan ]