String is immutable for several reasons, here is a summary:
-
Existence of String Constant Pool
Every application creates too many string objects and in order to save JVM from first creating lots of string objects and then garbage collecting them. JVM stores all string objects in a separate memory area called String constant pool and reuses objects from that cached pool.
Whenever we create a string literal JVM first sees if that literal is already present in constant pool or not and if it is there, new reference will start pointing to the same object in SCP -
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).
欢迎到作者github主页交流