//net 6 ....(as + and concatenation operations are stringbuffer operations and the final thing is converted to string)
Eric Zanders
Greenhorn
Joined: Sep 15, 2004
Posts: 16
posted
0
Rohan,
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.
Eric Zanders
Greenhorn
Joined: Sep 15, 2004
Posts: 16
posted
0
Thanks Paul. So returning to the initial question, the result (number of String objects) then should be 6?
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
posted
0
I count at least 9:
Remember that String objects are created for each of the literals in the code.
Remember that String objects are created for each of the literals in the code.
Layne[/qb]<hr></blockquote>
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 ]
I would recommend to read this article about Strings on javaranch itself, this is very nice article and definitely you will get answer to your question.
Gravitation cannot be held responsible for people falling in love ~ Albert Einstein