Reputation: 2679
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 );
Upvotes: 5
Views: 2961
Reputation: 6333
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.
Upvotes: 7
Reputation: 4923
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.
Upvotes: 0
Reputation: 302
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).
Upvotes: 3