Strings are immutable but How?

We all know Strings are immutable but how:

When we create String from string literal like String s = "Ishaan"; it goes into separate area in heap called String Literal pool. Afterward any creation of string "Ishaan"  in such way return the same reference as we have. Now say your application is using 100 references of the same string s if string would be mutable it could be changed by malicious code and your whole application got crashed.

Another example you can take is say you have developed  a web application a gmail kind of application and your name is "Ishaan" when you sign in you get your name displayed on right top. This name must be coming from String literal pool since you should not be interested in creating String using new operation as it create new object in heap. So now your name is "Ishaan" which may belongs to another user of you email application or millions of people infact if your app is popular. So think in this case if String would be mutable millions of people starts getting wrong name .I hope this is more clear to any one here.

Problem for Hash Map

String was made final so that no one can compromise invariant of String class e.g. Immutability, Caching, hashcode calculation etc by extending and overriding behaviors.

Another reason of why String class is immutable could die due to HashMap.

Since Strings are very popular as HashMap key, it's important for them to be immutable so that they can retrieve the value object which was stored in HashMap. Since HashMap works in the principle of hashing, which requires same has value to function properly. Mutable String would produce two different hashcodes at the time of insertion and retrieval if contents of String was modified after insertion, potentially losing the value object in the map.

No comments:

Post a Comment