Wednesday, January 17, 2018

Why String Is Immutable In Java

There are so many reasons to make String immutable in java.

If you observe , most of the time we used to work on Strings in Java applications. It means Strings playing wider role in Java programming.

Here I have mentioned what made String Immutable:

Security: parameters are typically represented as String in network connections, database connection urls, usernames and 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="Hello", and B="Hello") 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).

No comments: