Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many objects will be created during this string operation?

Tags:

java

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?

like image 359
M Sach Avatar asked Dec 12 '25 12:12

M Sach


1 Answers

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.

like image 63
Sergey Kalinichenko Avatar answered Dec 14 '25 17:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!