Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does StringBuilder creates a new String in every operation?

How many objects were created with this code? - I know the 3 String literals are in the String Constant Pool and the StringBuilder object is at the heap but does it creates a new String in the pool when i call reverse(), insert() or append() ?

StringBuilder sb = new StringBuilder("abc");
sb.append("def").reverse().insert(3, "---");
System.out.println( sb );
like image 901
GabrielBB Avatar asked Feb 28 '14 18:02

GabrielBB


2 Answers

StringBuilder will only create a new string when toString() is called on it. Until then, it keeps an char[] array of all the elements added to it.

Any operation you perform, like insert or reverse is performed on that array.

like image 101
wizulus Avatar answered Nov 20 '22 07:11

wizulus


Strings created: "abc", "def", "---"

StringBuilders created: sb

sb.append("def").reverse().insert(3, "---") are not creating new objects, just editing the StringBuilder's internal buffer (that's why using StringBuilder is recomended for performances).

like image 23
Bobby Avatar answered Nov 20 '22 06:11

Bobby