Reputation: 34424
Below is code snippet in instance method
String x = new StringBuffer().append("a").append("b").append("c").toString()
i am under impression , first new stringbuffer is created, then a is appended atlast of string buffer, similarly b and c. After that stringbuffer is converted to string. So as per me 2 objects are created(one for string buffer and another for string). correct? Basically as per me no intermediate objects will be created for String "a","b","c". Is this right?
Edit:- as per all of the replies, looks like objects will be created for string literals "a","b","c" But if i go by link http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/StringBuffer.html#toString(), this should not create temporary strings. Search "Overall, this avoids creating many temporary strings." on this link. Agreed it is for 1.4.2 but i hope fundamental remain same for 1.6
Yes if i do below instead of above five objects will be created. three for "a","b","c" . one for string buffer. Then at last for string converted from stringbuffer. objects for "a","b","c" and lastly string "abc" will go too pool and be there in for life time
String str1="a";
String str2="b";
String str3="c";
String x = new StringBuffer().append(str1).append(str2).append(str3).toString()
Is above understanding correct?
Upvotes: 3
Views: 1274
Reputation: 20059
The strings "a", "b", "c" are literals in both your code snippets. They will be created by the class loader before your code can execute, and there is no way (and normally also no point) to avoid that.
So both code snippets essentially do the same and they both create the same number of objects.
And, BTW neither of the snippets is valid code - you can not assign StringBuffer = String as you do in the last statement in both snippets.
EDIT: You also ask about Java versions >1.4. From Java5 up, StringBuffer should be replaced with StringBuilder (it does essentially exactly the same, but it is not synchronized, thus it performs a little better).
Upvotes: 1
Reputation: 75906
As pointed out in other answers, your two snippets are equivalent (regarding String object creation). The would be different instead if the second snippet were written as:
String str1= new String("a");
...
Only in this case you are guaranteed to have a new String object instantiated (not that you'd normally want that). See also here.
Upvotes: 1
Reputation: 726539
There is no difference between your first and second snippet in terms of how many objects are created. Strings "a"
, "b"
, and "c"
will participate in the process, although their interned copies may be used. In the absence of further references to str1..str3
, the compiler is free to transform your second snippet into your first one, eliminating the variables.
In addition, there may be an internal reallocation inside StringBuffer
's append
, if the memory in its internal string is insufficient to hold the data being appended. This is only a theoretical possibility, but it is there.
Upvotes: 3