Is “new String()” immutable as well?

后端 未结 15 2402
日久生厌
日久生厌 2020-12-12 23:43

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

15条回答
  •  时光说笑
    2020-12-13 00:05

    String is immutable irrespective of how it is instantiated

    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.

    Immutability allowed String pool or caching

    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 Strings 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:

    • Immutability benefits of String

提交回复
热议问题