Thursday 13 December 2018

Why String is Immutable




So that , by changing the Object reference , doesn't actually alter the desired behavior , like above.

In above example:
While storing a Key, we passed a String reference variable, which was pointing to "hk" during insertion, so the contract with retriver was make, that you mst use this key to retrieve the object, but suppose after 1 year, one simple line is added after insertion, S1.uppercase(),

If String was mutable, the key in HashCode, would have got changed.

If Java changed the actual value/key of hashtable, while user changes the reference, then if some client does hm.get("hk"), it would give Null, hence undesirable behavior.

Similar issues arises if you use String as some URL, leads to security concerns for your application.

Credits : https://www.youtube.com/watch?v=ZMfMMbEzKE4


No comments:

Post a Comment