Popular Feed

String Pool in Java

The Java String Pool avoids creating unnecessary String objects as it reuses the existing String objects.

Therefore the Java String Pool has a significant impact on improving the memory and the application

performance/ utilization of Java String objects.

what happens when we use different ways to create Strings.

String Pool is possible only because String is immutable in Java. The String pool is also an example of

Flyweight design pattern.

String s1="Hello";

String s2=s1;

String s3="Hello";

When we use double quotes to create a String, it first looks for String with the same value in the

String pool, if found it just returns the reference else it creates a new String in the pool and then

returns the reference.

String s4= new String("Hello");

String s5= new String("Hello");

However using a new operator, we force String class to create a new String object in heap space.

We can use intern() method to put it into the pool or refer to another String object from the string

pool having the same value.

java string pool

Before Java 7, the JVM placed the Java String Pool in the PermGen space, which has a fixed size — it can't be expanded at runtime and is not eligible for garbage collection.

The risk of interning Strings in the PermGen (instead of the Heap) is that we can get an OutOfMemory error from the JVM if we intern too many Strings.

Note: From Java 7 onward, the Java String Pool is stored in the Heap space, which is garbage collected by the JVM. The advantage of this approach is the reduced risk of OutOfMemory error because unreferenced Strings will be removed from the pool, thereby releasing memory.

No comments: