Table of Contents
// Output will be
This explains that String is immutable in nature.
String pool :
If you simply assign a Value to String using double quotes, it is stored in area called string literal pool and one string can be referenced by many reference variables and if String Is mutable, then it will affect all reference variables.
Thread safe :
Immutable objects are by default thread safe, so you don’t need to put synchronisation for it and String instance can be safely shared among multiple threads.
If String is not immutable then it may cause multiple security issue.
For example, while connecting to database, you provide username, password, Port and host name etc as String, if String is mutable, any hacker can change the reference value and cause security threats to application.
Cache hash value :
When you use String as key in HashMap or HashSet or any other collection, you can cache it’s hash value. As String is immutable in nature, you don’t need to calculate each time as it will be constant. It greatly improve performance for this hash based collections.
Class loading :
String is used as class loading mechanism. It is passed as a parameter. If String is mutable, it is a security threat as any hacker could have changed it.