Wednesday 29 July 2015

Why String is Final in Java?

     1) 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.

It’s at all because 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.

     2) String has been widely used as parameter for many Java classes e.g. for opening network connection (hostname and port number) , database URL to opening database connection, open any file in by passing name of file as argument to File I/O classes.

In case, if String is not immutable, this would lead serious security threat, Someone can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file.

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

    3) 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.
   
   4) 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.

String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

5) 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...