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 );
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With