Why is String Immutable ?

String in a class it is used to holding the array of characters. The difference between String and StringBuffer is String is immutable where as StringBuffer is mutable. Means we can not change the value of the string.

Why it so?

Actually in java, Strings are handling in Pool format.

For example:

String str1 = “xyz”;

This string(str1) will be stored into memory in particular address. When we defining new String with same array of characters like

String str2 = “xyz”;

Now JVM will check in String Pool where there is same characters are available or not. If two Strings are match the JVM will refer str1 address to str2. Now the str1 and str2 referring the same characters in same memory location. This is a good idea for increasing memory efficiency.
When we change the str1 characters, the changes will be reflected to str2. Because both str1 and str2 variables are referring the same memory location. For avoiding this we are keeping String as immutable. However we can use StringBuffer if you want to do modifications in the string.

Advantages of Immutablitiy

  • You can share immutable objects between threads without danger of changes confusing the other thread. You don’t need any locking. Two threads can both work on an immutable object at the same time without any possibility of conflict.
  • Once you check the value, you know it has to stay safe. No one can pass you a value, then behind your back swap it to an unsafe one using a background thread. This is particularly important in high security situations where allowing an invalid value to sneak in could compromise system integrity, e.g. a filename. This is probably the main reason that Strings are immutable.
  • You can share duplicates by pointing them to a single instance. You need only one copy, e.g. String interning. This saves RAM. With mutable StringBuilders that were temporarily identical, you could not throw one away, and replace it with a reference to the other, since at any moment their values could diverge again.
  • You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret behind Java’s very fast substring implementation.
  • Immutable objects are much better suited to be Hashtable keys. If you change the value of an object that is used as a hash table key without removing it and re-adding it you lose the mapping.
  • 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.

No comments:

Post a Comment