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

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top