immutable String by R4R Team

 Immutable Java String:

Java String is a immutable object. For an immutable object you cannot modify any of its attribute’s values. Once you have created a java String object it cannot be modified to some other object or a different String. References to a java String instance is mutable. There are multiple ways to make an object immutable. Simple and straight forward way is to make all the attributes of that class as final. Java String has all attributes marked as final except hash field.

Java String is final. I am not able to nail down the exact reason behind it. But my guess is, implementors of String didn’t wany anybody else to mess with String type and they wanted de-facto definition for all the behaviours of String.
 

few advantages of String Immutability / Final in Java:

1)Security: the system can pass on sensitive bits of read-only information without worrying that it will be altered.
2)It simplifies multithreaded programming since reading from a type that cannot change is always safe to do concurrently. We can share duplicates by pointing them to a single instance.
3)You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret of Java’s very fast substring implementation.
4)Immutable objects are better suited to be HashTable keys. If you change the value of an object that is used as a HashTable key without removing it and re-adding it you lose the mapping.
5)Since String is immutable, inside each String is a char[] exactly the correct length. Unlike a StringBuilder there is no need for padding to allow for growth.
6)It allows for a reduction of memory usage by allowing identical values to be combined together and referenced from multiple locations. Java performs string interning to reduce the memory cost of literal strings embedded in code.
7)It simplifies the design and implementation of certain algorithms (such as those employing value-space partitioning or backtracking) because previously computed state can be reused later.
Leave a Comment: