Skip to content
Advertisement

How many objects are created in StringBuilder?

Based on my understanding on String objects, that every string literal is being added/created on the String Constant Pool.

String a = new String("hello world");

two objects are being created, one is the “hello world” being added on the constant pool and the other object is the new instance of String. Does the same principle is being applied when it comes to StringBuilder?

StringBuilder b = new StringBuilder("java is fun");
b.append(" and good");

in the StringBuilder example does it mean that there are 3 objects being created? The first one is the new instance of StringBuilder and the other 2 objects are the string literals “java is fun” and ” and good”?

Advertisement

Answer

Yes, your understanding is correct. (But see below.) String literals go in the constant pool, while the new String(...) and new StringBuilder(...) create additional objects. (The StringBuilder also creates an internal character array object, so that there are at least four objects involved in the second example.) Note that the call to b.append(...) may internally create another object and some garbage, but only if the internal character array used by b needs to expand.

EDIT: As @fdreger points out in a comment, the string objects corresponding to the string literals are created not at run time, but rather at the time the class is created during the creation and loading phase of the class life cycle (as described in the Java Language Specification; see also the section on the runtime constant pool).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement