I\'ve been studying Java String for a while. The following questions are based on the below posts
Java String is special
Immutability of String in java
1) Short answer is yes, new String()
is immutable too.
Because every possible mutable operation (like replace
,toLowerCase
etcetra) that you perform on String
does not affect the original String
instance and returns you a new instance.
You may check this in Javadoc for String
. Each public
method of String
that is exposed returns a new String
instance and does not alter the present instance on which you called the method.
This is very helpful in Multi-threaded environment as you don't have to think about mutability (someone will change the value) every time you pass or share the String
around. String
can easily be the most used data type, so the designers have blessed us all to not think about mutability everytime and saved us a lot of pain.
It is because of immutability property that the internal pool of string was possible, as when same String value is required at some other place then that immutable reference is returned. If String
would have been mutable then it would not have been possible to share String
s like this to save memory.
String immutablity was not because of pooling, but immutability has more benefits attached to it.
String interning or pooling is an example of Flyweight Design pattern
2) Yes it will be interned like any other String
as a blank String
is also as much a String
as other String
instances.
References: