Why String is Immutable or Final in Java

 The String objects are cached in the String pool, and it makes the String immutable

  • The cached String literals are accessed by multiple clients. 
  • So, there is always a risk, where action performs by one client affects all other clients. For example, if one client performs an action and changes the string value from vds to VDS , all remaining clients will also read that value. For the performance reason, caching of String objects was important, so to remove that risk, we have to make the String Immutable.

String is immutable because of multiple reason:

  • Security: 
    • parameters are typically represented as String in network connections, database connection URLs, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
  • Synchronization and concurrency: 
    • making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching: 
    • when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
  • Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).
That being said, immutability of String only means you cannot change it.


THANKS!!


Comments

Popular posts from this blog

Python namespaces & LEGB rule in Python