Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Questions about Java's String pool [duplicate]

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?

like image 612
andandandand Avatar asked Dec 10 '09 15:12

andandandand


1 Answers

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).

like image 145
Jesper Avatar answered Sep 21 '22 20:09

Jesper