Search code examples
javastringjvmstring-pool

Java - Unpooled String


  • Is there a legal way to force JVM not to store particular String instance in a long-lived string pool?

  • Does new String() provide this feature and I can be 100% sure that value created this way will be put into the heap and not into the pool unless I call intern()?


Solution

  • Is there a legal way to force JVM not to store particular String instance in a long-lived string pool?

    Other than not initializing it with a string literal, I'm afraid there isn't.

    Does new String() provide this feature and I can be 100% sure that value created this way will be put into the heap and not into the pool unless I call intern()?

    Yes (keep in mind that if you write String str1 = new String("Hello");, then the String instance referred to by str1 will not get internalized, while the String instance created for the literal string "Hello" will).

    Also note that where exactly the pool gets stored in the heap depends on the version of the JVM as explained here