We will find answers for the following questions
- What is String pool?
- How does memory allocation work for String?
- Why is String immutable.
String pool is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
Does that make sense ??? If not don’t worry.
The following example will help you to understand it.
This line will look for Hello String in String Pool. If it doesn’t exist will create one, containing “Hello” and assign it a reference myStr.
In this case a new reference newStr is created which will point to same String object as it already exist in String pool.
When the above statement is executed, the JVM takes the value of String newStr, i.e. “Hello” and appends ” World”, giving us the value “Hello World”.
Now, since Strings are immutable, the JVM can’t assign this value to newStr, so it creates a new String object in the String pool with value “Hello World” and gives it a reference newStr.
An important point to note here is that, while the String object is immutable, its reference variable is not.
Putting them all together
Give special attention to Hashcode value. If Hashcode changes, new memory is allocated in Heap Memory, in this case, String Pool.
This example answers our 1st and 2nd Question. Now you can go ahead and read String Pool Description written above.
Notice the last String variable test. As “Hello” was already in String Pool, JVM just created a reference to it. This way JVM reused String objects efficiently.
For 3rd Question.
In the String constant pool, a String object is likely to have one or many references.
If several references point to the same String without even knowing it, it would be bad if one of the references modified that String value. That’s why String objects are immutable.
This feature helps in many ways
- It is safe for multi-threading and a single String instance can be shared across different threads.
- Its hashcode is cached at the time of creation and it doesn’t need to be calculated again.
- This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects.