String Pool in Java and String Initialization

How to Create a String

As we know that String in java can be created using 2 types.
1. Direct initialization
String textString = "This is test";

2. Using a new operator
String textString = new String("This is test");

Difference between these 2 types

Before going to the differences, we will first understand the concept of String Pool.

What is a String Pool in Java

String Pool in Java is an area on the Java Heap memory that contains a pool of strings.

Whenever a String is created using the double quotes (1st method as shown above), the JVM checks for the String in the Java Heap memory.
If a String with the same value is found, then only the reference of the String that is already present is pointed to the new String that we want to create.

String Handling in Java Program with Examples | String Pool in Java and String Initialization

As you can see in the above image, When creating String str4 = "Apple"; , Since it was already available in the String Pool, only reference was pointed to original value in String Pool.

As string is immutable , when you try to modify the value of the String that you have created from String Pool, a new String is created or reference from String Pool.

example:

We have “Apple” in the String Pool. Now we add something to str4. The output will be Apple is good

But internally String Pool will create a new value in String Pool and assign to str5, as shown in below image.

String Manipulation in Java Programs | String Pool in Java and String Initialization

Using new Operator and Effect on String Pool

When a String is created using “new”, (2nd method as shown above), a new string is created in the Java Heap memory. Even though “Apple” was available in String Pool , yet another String was created in Java Heap Memory.
Every time you create a new String using this method, a new String will be created in Java Heap memory. This string will be sitting in the Java Heap memory until the garbage collector collects it. This can cause slow performance.
String Sample Code in Java | String Pool in Java and String Initialization

Even if you create a String using “new” keyword, we can add this String in String Pool using String.intern()

Advantages of String Pool

As you can see creating a string using the double quotes – String str1 = “Apple”; is much more faster and creating a String using “new” operator due to use of String Pool.
Also String Pool helps the java heap memory to be used optimally, as few Strings are created on the Java Heap. This helps in less work for the garbage collector.

Reference

1. String API -http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn