one thing that i always wondered, if i have a method like this:
String replaceStuff (String plainText) {
return plainText.replaceAll("&", "&");
}
will it create new String objects all the time for the “&” and the “&” that gets destroyed by the GC and then recreated again by next call?
E.g.
would it in theory be better to do something like this
final String A ="&";
final String AMP ="&";
String replaceStuff (String plainText) {
return plainText.replaceAll(A, AMP);
}
i think this is probably a more theoretic question than a real life problem, I am just curious how the memory management is handled in this aspect.
No. String literals are interned. Even if you use an equal literal (or other constant) from elsewhere, you’ll still refer to the same object:
EDIT: The JLS guarantees this in section 3.10.5
Section 15.28 shows the + operator being included as an operation which can produce a new constant from two other constants.