Is “new String()” immutable as well?

后端 未结 15 2486
日久生厌
日久生厌 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:08

    The Java libraries are heavily optimized around the constraint that any String object is immutable, regardless of how that object is constructed. Even if you create your b using new, other code that you pass that instance to will treat the value as immutable. This is an example of the Value Object pattern, and all of the advantages (thread-safety, no need to make private copies) apply.

    The empty string "" is a legitimate String object just like anything else, it just happens to have no internal contents, and since all compile-time constant strings are interned, I'll virtually guarantee that some runtime library has already caused it to be added to the pool.

提交回复
热议问题