Koekiebox
Koekiebox

Reputation: 5963

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.

Meaning my question boils down to this:

  1. Will the Java String pool always be used when and when I don't declare a String variable using the new keyword?

  2. Is it better to declare a String as a variable before using it?

  3. 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?

Upvotes: 1

Views: 663

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

  1. All literal Strings are interned.
  2. Write code that is easy to understand. It really is not worth trying to nano-optimise this.
  3. All literal Strings loaded by class loaders are interned, as are Strings returned by String.intern (which is a slow way of doing it, in typical implementations).

Upvotes: 10

Related Questions