Why String is immutable in java

Previous
Next
String class is immutable in java. If you take dictionary meaning of immutable, it means unable to be changed or unchanging over time, so String is unchangeable or unmodifiable in java.
Let’s understand with example.

As you can see, value of str1 did not change. It created another String object with value “Hellojava2blog” but did not change String str1

This explains that String is immutable in nature.

Now let’s understand what are potential reasons to make string immutable in java

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.

Security :

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.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog