Posts
Showing posts from February, 2022
Why String is Immutable or Final in Java
- Get link
- X
- Other Apps
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...