tags:

views:

225

answers:

3

What is meant by String Pool ? What is difference between the following declarations :

String s="hello"; String s=new String("hello");

Is there any difference between the Storing of this two strings by JVM ?

+5  A: 

The string pool is the JVM's particular implementation of the concept of string interning:

In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.

Basically, a string intern pool allows a runtime to save memory by preserving immutable strings in a pool so that areas of the application can reuse instances of common strings instead of creating multiple instances of it.

As an interesting side note, string interning is an example of the flyweight design pattern:

Flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.

Andrew Hare
+1  A: 

String pool is exactly that: a pool of strings. If you use "hello" again, it will check the string pool and grab it there if it exists. Otherwise, it will create a new one. the String constructor always creates a new one. You can check this for yourself by creating lots of "blah" strings in a for loop and using the == operator to check reference equality.

Chris Dennett
+1  A: 

The string pool allows string constants to be reused, which is possible because strings in Java are immutable. If you repeat the same string constant all over the place in your Java code, you can actually have only one copy of that string in your system, which is one of the advantages of this mechanism.

When you use String s = "string constant"; you get the copy that is in the string pool. However, when you do String s = new String("string constant"); you force a copy to be allocated.

Michael Aaron Safyan