Question

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 );
Was it helpful?

Solution

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.

OTHER TIPS

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).

StringBuilder sb = new StringBuilder("abc");
sb.append("def").reverse().insert(3, "---");
System.out.println( sb );

Only 1 Object of StringBuilder will be created in the heap, no matter which ever method provided by the class is used like append,reverse etc.

The memory once allocated will not be changed whether you use toString() method to cast it into String.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top