It is special storage 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. Below both strings are same and pointing to the same object in String Pool:
Stringmystring1="String is immutable";
Stringmystring2="String is immutable";
You can used relational equality operator ‘==’ to compare references of two strings in above case. String is immutable, it is not efficient to use String if you need to modify your String frequently (that would create many new Strings occupying new storage areas).
Heap Space for String Object :
Every String object in the heap has its own storage like any other object. There is no sharing of storage in a heap even if two String objects have the same contents.
Stringmystring1=newString("It is stored in heap");
We have to use equals method to compare string. It is uncommon and not recommended to use the new operator to construct a String object in the heap.
We can cache hashcode of string. As string is immutable and value of string in pool is not going to change. Same logic applies to hashmap, as hashmap doesn’t require to calculate it’s key hashcode every time.
Strings are implicitly thread safe. Since String is immutable we do not require to synchronize objects if it is shared between multiple threads.
String prevents security threats. Strings are used in many applications i.e. database connection, file opening, network connections etc.
If string is not immutable, someone can change the value of String and change the host URL and password and gain access to the system. As java.lang.String is final no one can override String Class.
String are useful in loading classes. For example if you are trying to load java.sql.Connection using driver of oracle and someone change its value to mysql driver which can do unwanted things.