String literals aren't created when the line that references them is being executed. String literals are created when a class is loaded.
Your first example will just create one new String. Your second example will create a new String for s2, and a new String for each concatenation operation, so that's 3 new objects in total. Note that one of those (the String created by s1 + s2) will become eligible for garbage collection after the expression is finished, because there are no references to it anymore.
prateek sharmaa
Ranch Hand
Joined: May 15, 2010
Posts: 38
posted
0
thanks Stephan, that was very much explanatory.
i have one more question that you said String literals are created at the time of class loading so shouldn't we count it as an object?
Stephan van Hulst wrote:... and a new String for each concatenation operation, so that's 3 new objects in total. Note that one of those (the String created by s1 + s2) will become eligible for garbage collection after the expression is finished, because there are no references to it anymore.
You're right that the concatenation will create two objects but they won't both be Strings. One will be a StringBuilder. The compiler is clever enough to optimise that bit of code into
In fact the compiler has the option to optimise it in any way it likes, so future versions of Java may optimise it differently. That's why it's recommended to always write
rather than
If a later Java version comes up with a better optimisation, the first bit of code will use that optimisation, but if you're explicitly using a StringBuilder then it won't.
Joanne Neal wrote:In fact the compiler has the option to optimise it in any way it likes, so future versions of Java may optimise it differently. That's why it's recommended to always write
Hmmm, "overloaded operator as a layer of indirection"... When will it end?
Winston
Isn't it funny how there's always time and money enough to do it WRONG?