Consider this code:
String first = "abc";
String second = new String("abc");
When using the new keyword, Java will create the abc String again right?
Will this be stored on the regular heap or the String pool?
How many Strings will end in the String pool?
If you use the
newkeyword, a newStringobject will be created. Note that objects are always on the heap - the string pool is not a separate memory area that is separate from the heap.The string pool is like a cache. If you do this:
then the Java compiler is smart enough to make just one
Stringobject, andsandpwill both be referring to that same String object. If you do this:then there will be one
Stringobject in the pool, the one that represents the literal"abc", and there will be a separateStringobject, not in the pool, that contains a copy of the content of the pooled object. SinceStringis immutable in Java, you're not gaining anything by doing this; callingnew String("literal")never makes sense in Java and is unnecessarily inefficient.Note that you can call
intern()on aStringobject. This will put theStringobject in the pool if it is not already there, and return the reference to the pooled string. (If it was already in the pool, it just returns a reference to the object that was already there). See the API documentation for that method for more info.See also String interning (Wikipedia).