Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

October 10, 2009

Why Strings are immutable

The basic reason is that we use String pool for String objects.So if we have a number of objects that have same value, all the reference variables would be pointing to the same value in the pool. So if string were nt immutable and somebody chaged that value, the value of all the objects pointing to that object would change, which is undesired.

You might wonder why Strings are immutable in first place. There are two very compelling reasons for it:

1. Immutable basic types makes things easier. If you pass a String to a function you can be sure that its value won't change.
2. Security. With mutable Strings one could bypass security checks by changing the value right after the check. (Same thing as the first point, really.)

Detailed Description :
http://kaioa.com/node/59

No comments: