What's the advantage of a String being Immutable?
Solution 1:
Immutability (for strings or other types) can have numerous advantages:
- It makes it easier to reason about the code, since you can make assumptions about variables and arguments that you can't otherwise make.
- It simplifies multithreaded programming since reading from a type that cannot change is always safe to do concurrently.
- It allows for a reduction of memory usage by allowing identical values to be combined together and referenced from multiple locations. Both Java and C# perform string interning to reduce the memory cost of literal strings embedded in code.
- It simplifies the design and implementation of certain algorithms (such as those employing backtracking or value-space partitioning) because previously computed state can be reused later.
- Immutability is a foundational principle in many functional programming languages - it allows code to be viewed as a series of transformations from one representation to another, rather than a sequence of mutations.
Immutable strings also help avoid the temptation of using strings as buffers. Many defects in C/C++ programs relate to buffer overrun problems resulting from using naked character arrays to compose or modify string values. Treating strings as a mutable types encourages using types better suited for buffer manipulation (see StringBuilder
in .NET or Java).
Solution 2:
Consider the alternative. Java has no const qualifier. If String objects were mutable, then any method to which you pass a reference to a string could have the side-effect of modifying the string. Immutable strings eliminate the need for defensive copies, and reduce the risk of program error.
Solution 3:
Immutable strings are cheap to copy, because you don't need to copy all the data - just copy a reference or pointer to the data.
Immutable classes of any kind are easier to work with in multiple threads, the only synchronization needed is for destruction.
Solution 4:
Perhaps, my answer is outdated, but probably someone will found here a new information.
Why Java String is immutable and why it is good:
- you can share a string between threads and be sure no one of them will change the string and confuse another thread
- you don’t need a lock. Several threads can work with immutable string without conflicts
- if you just received a string, you can be sure no one will change its value after that
- you can have many string duplicates – they will be pointed to a single instance, to just one copy. This saves computer memory (RAM)
- you can do substring without copying, – by creating a pointer to an existing string’s element. This is why Java substring operation implementation is so fast
- immutable strings (objects) are much better suited to use them as key in hash-tables