Reputation: 977
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"?
Upvotes: 2
Views: 1332
Reputation: 234795
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).
Upvotes: 3
Reputation: 12495
The strings are created when the class is loaded, not when the actual code is executed. You may think of them as part of your code, exactly as any other literal value.
So in your second example:
Upvotes: 1
Reputation: 6403
Yes, you're right.
"java is fun"
and " and good"
are going to be stored in the constant pool. I would call them objects, but yes, it's more like it.
b
in this case is going to be an object with a limited lifespan. It may actually store its own copy of both strings in its buffer to work with, so that originals won't be modified.
Upvotes: 0