5 January 2014

Why String is immutable in Java?

One of the most common question(on exams,interview), which has one of  most blurry answers.

So.. Why bloody String  is immutable in Java?

There are few known to me reasons why (with explanations and resources):


  • Design decision  (immutable  Strings cause much less trouble to implement many features in Java like cache, HashMap)
  • Security 
  • Optimization
  • Concurrent purposes (multi-threading


Design decision and optimization:
James Gosling: I would use an immutable whenever I can.
Bill Venners: Whenever you can, why?
James Gosling: From a strategic point of view, they tend to more often be trouble free. And there are usually things you can do with immutable that you can't do with mutable things, such as cache the result.
Another thing about immutable objects: if you have a class that's final and whose fields are final, except for one nasty problem, the optimizers can do really cool things with them, because they don't necessarily have to allocate them in the heap. They can have pure stack lifetime. You can copy them at will. You can replicate them at will, which is what happens with primitives.
Another thing about immutable objects: if you have a class that's final and whose fields are final, except for one nasty problem, the optimizers can do really cool things with them, because they don't necessarily have to allocate them in the heap. They can have pure stack lifetime. You can copy them at will. You can replicate them at will, which is what happens with primitives.
That's one of the reasons that primitives are not objects, because it is so nice to be able to just replicate them. When you pass an integer to a method, you don't have to pass the pointer to that integer.

Security:

James Gosling "One of the things that forced Strings to be immutable was security. You have a file open method. You pass a String to it. And then it's doing all kind of authentication checks before it gets around to doing the OS call. If you manage to do something that effectively mutated the String, after the security check and before the OS call, then boom, you're in. But Strings are immutable, so that kind of attack doesn't work. That precise example is what really demanded that Strings be immutable."
 String and Cache its Hashcode:
Ryan Wang The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.  

Concurrent purposes (multi-threading):

(I lost sources for that :( )

So remember .It was a design decision to make String  immutable for security ,optimization and concurrent  purposes.

Sources:
http://www.artima.com/intv/gosling3.html
http://java.dzone.com/articles/why-string-immutable-java