Why Strings are Immutable in Java?
Muhammad Wasi Naseer
Posted on December 12, 2021
Before understanding why strings are immutable in java, we need to think about why do we make something immutable?
Immutable means once created we cannot change it. The one reason that we can think of making anything immutable is synchronization when it’s shared. It’s the same reason that strings are immutable.
In Java, String objects are shared and cached in String Pool. It’s a designated place in a heap where strings are stored and shared among multiple threads if they have the same value. For example: In String Pool, if there is already a string with the value “test” and the program wants to create another string object with the same value then it will get the same reference instead of creating a new string object. Now we know how strings are stored in heap. Let’s look at the reasons why they are immutable.
The first reason is to make it thread safe. Since strings are shared among multiple threads in string pool, we need to restrict any random thread to change it. Any change in a string can be impacted to other threads which are accessing the same string. If a thread wants to update the value of a string, it needs to create another string and takes it reference.
Usually, we use String as a key in Map. If Strings were mutable, anyone can change the value of the strings, and we would lose the actual key.
Posted on December 12, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.