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?