Thursday, October 2, 2008

Why Strings are immutable?

From all the objects in the java world the String object is the most exceptional one. It's the only object that you can use the operators + and += on it. This is the only object that you can define like String myString = "moshe". And the most important feature that affects all of us is that Strings are immutable? Why? What so special in Strings and why it's not like it in different languages? In fact strings are very important and unique objects in java for the following reasons:
Java is the internet and networking language. Therefore, we will need a language that supports reading text very well. Therefore, we don't want to allocate new string for every string object. The solution: java creates a constant pool for strings each string that is allocated in compile time is allocated in the pool so we will reduce creation of redundant object. Therefore, the string must be immutable, since if not changing in one reference of the string will change the string in other references of the program.
Since string is so basic in java, the java developers would like to give the string the essence of primitive. Since string is immutable it looks like it pass by value for a method (if the string has changed is no longer the same object) so String is immutable like all the other wrappers of the primitives.
Since Strings are very popular mainly for configuration, it is highly important that the String will be thread safe without paying the cost of synchronization therefore, using immutable object is highly recommended here.
String is one of the basic objects in java this is why it's so unique. It is highly important to understand its place in the java world.