Questions about Java's String pool [duplicate]

If you use the new keyword, a new String object 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:

String s = "abc";
String p = "abc";

then the Java compiler is smart enough to make just one String object, and s and p will both be referring to that same String object. If you do this:

String s = new String("abc");

then there will be one String object in the pool, the one that represents the literal "abc", and there will be a separate String object, not in the pool, that contains a copy of the content of the pooled object. Since String is immutable in Java, you're not gaining anything by doing this; calling new String("literal") never makes sense in Java and is unnecessarily inefficient.

Note that you can call intern() on a String object. This will put the String object 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).


In bytecode, the first assignment is:

  Code:
   0:   ldc     #2; //String abc
   2:   astore_1

whereas the second is:

   3:   new     #3; //class java/lang/String
   6:   dup
   7:   ldc     #2; //String abc
   9:   invokespecial   #4; //Method java/lang/String."":(Ljava/lang/String;)V

So the first is in the pool (at position #2) whereas the second will be stored in the heap.

EDIT

Since the CONSTANT_String_info store the index as U2 (16 bits, unsigned) the pool can contain at max 2**16 = 65535 references. In the case you care here more limits of the JVM.


Each time your code create a string literal

for example:

String str="Hello"; (string literal) 

the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption