Introduction :
Strings are immutable in java which means once we create a string object we can not perform any changes in the existing object. If we are trying to perform any changes with those changes a new object will be created. This non-changeable behavior is nothing but immutability of strings.
In Java, we can create a String object in 2 way.
1) By using new keyword
2) By using String literal

Security :
String is commonly utilized in Java applications. Strings are used to hold sensitive data such as connection URLs, usernames, and passwords. All of this information is passed as the string object. Now, suppose if string object is not immutable in nature, then it would cause a serious security threat to the application because these values are allowed to get changed. To prevent this sun people has given strings are immutable means we can’t change any thing in the existing object.
Thread Safety :
An object is called thread-safe when multiple threads are operating on it but none of them is able to corrupt its state and object hold the same state for every thread at any point in time. As we an immutable object cannot be modified by anyone after its creation which makes every immutable object is thread safe by default. We do not need to apply any thread safety measures to it such as creating synchronized methods. So due to its immutable nature string object can be shared by multiple threads and even if it is getting manipulated by many threads it will not change its value.
HashCode Caching :
If we are going to perform any hashing related operations on our object we must override the hashCode() method and try to generate an accurate hashcode by using the state of the object. If object’s state is getting changed which means its hashcode should also change. Because Strings are immutable so the value one string object is holding will never get changed which means its hashcode will also not change which gives String class an opportunity to cache its hashcode during object creation.