Reputation:
public String toString()
{
return "NotSubscribed";
}
We are trying to limit String's creation in our application after the objects are instantiated. So, just wondering if this creates a new String every time this toString is called. It might be a bad question, but I don't know the answer. Please suggest.
--
I just remembered that if a String is created, it is stored in the String Pool and after that it is always retrieved from the pool without being re-created. Am I right?
Upvotes: 3
Views: 482
Reputation: 1500055
No, that won't create another string each time. String constants are interned - so actually the constant "NotSubscribed" will refer to the same string object throughout your code, not even just every time this method is executed.
From section 3.10.5 of the Java Language Specification:
Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.
However, in your edit:
I just remembered that if a String is created, it is stored in the String Pool and after that it is always retrieved from the pool without being re-created. Am I right?
No, that's not right. Only string constants are interned by default. For example, every time you run this code:
public List<String> createStrings() {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
list.add("foo" + i);
}
return list;
}
... that will create another 10 strings.
Upvotes: 9