Tuesday, September 18, 2012

Why String is Immutable?


Immutable means unchangeable. Value objects (numbers, characters, boolean and text) are unchangeable.

Value Objects :
numbers :  1, 2, 3, 4, 5, …
booleans : true, false
characters:  a, b, c , d, e, …
text values: "abc", "bcd", "123", "a12", "1ad", …

Numbers, Characters and Booleans are represented by Wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, Boolean).

And text is represented by String So it has implemeted as immutable.

And we have following advantages by immutability for String:

To ease multi-threading, multi-networking and thread safety :  It gives the  guarantee that,  string object can be shared between threads or networks as  these are not modified.

To support pooling :  We can share objects  across multiple references.

To support security:  Data once passed will not be changed for passwords, filenames, urls, class names for Class Loading Mechanism.

No comments:

Post a Comment