2
Reply

Why String is immutable in Java

Javin Paul

Javin Paul

14y
5.8k
0
Reply


    1)Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

    String A = "Test"
    String B = "Test"

    Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

    2)String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as stirng , you can pass database URL as string for opening database connection, you can open any file 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 , I mean some one 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.

    3)Since String is immutable it can safely shared between many threads ,which is very
    important for multithreaded programming.

    for detail see here
    http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html