Java String best practice regarding pool
I have always wondered what the most effective way is of creating String's in Java. By this I mean strings that won't change in value.
Example:
String prefix = "Hi, I am ";
The prefix
won't change but the postfix might.
I don't want to make the
prefix
astatic final
variable as it will always stay alive in the JVM even if the class is rarely used...bla bla.and when I do the following:
String fullWord = ("Hi, I am "+_postFix);
开发者_JAVA技巧I am guessing that the
"Hi, I am"
String value will remain in the Java String pool and I don't have the "overhead" of declaring the prefix as a variable.
Meaning my question boils down to this:
Will the Java String pool always be used when and when I don't declare a String variable using the
new
keyword?Is it better to declare a String as a variable before using it?
How does the String pool work? Does the JVM detect that a same String value is often used and keeps referring to that String in JVM memory?
- All literal
String
s are interned. - Write code that is easy to understand. It really is not worth trying to nano-optimise this.
- All literal
String
s loaded by class loaders are interned, as areString
s returned byString.intern
(which is a slow way of doing it, in typical implementations).
精彩评论