The above two Questions are related as Immutable --> final
consider the below scenario If String is not a Final Class
i had a String Object String super="Java";
i have two subclasses of String super( parent Class) Class A and Class B.if Class A changes its reference to A="J2EE" then the reference of Class B also points to J2EE.which is not a thread safe.
Some of the reasons why it made as Immutable :
- The designers wanted to guarantee that the invariants of String could not be changed by a sub-class. To guarantee that String itself would not change they implemented parent delegation in class loaders
- Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.
- The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.As in JVM String is mostly used parameter for loading classes or opening the connections.
- and one more reason is for thread safety.