Sunday, 9 June 2019

Core Java | Why String is Immutable(Final) in Java?

String pool facility without making string immutable: not possible.

         String a = "Common";
         String b = "Common";

Now String b called "Common".toUpperCase() which change the same object into "COMMON", so a will also be "TEST" which is not desirable. In case of string pool one string object/literal e.g. "Common" has referenced by many reference variables, so if any one of them change the value others will be automatically gets affected.


String has been widely used as the parameter for many Java classes e.g. for opening network connection (hostname and port number), database URL to opening a database connection, open any file in by passing name of the file as an argument to File I/O classes. In case, if String is not immutable, this would lead to a serious security threat. Someone can access to any file for which he has authorization, and they can change the file name either deliberately or accidentally and gain access to those files.

java.lang.String final ensured that no one overrides any behavior of String class.

Thread safety

Immutable classes are thread safe in Java since String can safely share among many threads and to avoid any synchronization issues, you don't need to synchronize String operation externally.


Java is to allow String to cache its hashcode, being immutable String in 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 string is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocations.

Class loading

The string is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...