Why String is immutable in Java?

String is immutable in Java for various reasons:

Security: If String is not immutable then this would lead to serious security threat it mean someone can access to any files that are used to store parameters like network connections, database connection URLs, usernames/passwords etc. If it were mutable, then these parameters could be easily changed.

Class Loading: String is used as arguments for class loading. If it is mutable then it will load wrong classes.

Synchronization: Immutable String is by default thread safe and hence it solves synchronization issues.

Caching: String cache its hashcode and do not produce hashcodes everytime when hashcode method of String is called, which makes it very fast as hashmap key to be used in hashmap in Java.

Java Professional with rich experience in Java development.
– Designing and developing high-volume, low-latency applications with high-availability and performance.
– Writing well designed, robust and efficient code.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By : XYZScripts.com