Why String is immutable in java?

 Let's understand about π‘Ύπ’‰π’š π‘Ίπ’•π’“π’Šπ’π’ˆ π’Šπ’” π’Šπ’Žπ’Žπ’–π’•π’‚π’ƒπ’π’† π’Šπ’ java?

What exactly does immutability mean?

If an object's state cannot change after it is created, it is said to be immutable.

Because of the following advantages, Strings are immutable in Java: 






String literals are stored in a special memory region called π‘Ίπ’•π’“π’Šπ’π’ˆ 𝑷𝒐𝒐𝒍 (𝑺𝑷) inside HEAP memory by JVM. Caching the String literals and reusing them saves a lot of heap space because different String variables refer to the same Object in SP.

Due to immutability, JVM optimizes the amount of memory allocated for Strings by storing distinct objects in SP. This process is called "interning".


String s1 = "Javaoneworld";

String s2 = "Javaoneworld";

First "Javaoneworld" will get stored into SP and s1 refers to that, Since "Javaoneworld" is already present in SP s2 will also refer to the same Object, By this process, JVM saves heap space.


A String is frequently used to hold users, connection URLs, and other data in a standard Java program. Assuming our function updateUserPasswordToDefault(String userName) executes the following operations,

1) Checks the username provided for security purposes

2) Creates a secure password using Java's built-in APIs.

3) Update the userName's password in the database table.

If Strings are mutable by the time we execute an update, we can't be certain of the String we received because it may get altered by our caller in between, leaving our query vulnerable to SQL injection in this situation. The method caller still has access to the userName object. Mutable Strings can therefore have a significant long-term influence on security.


Since the String is immutable, it is naturally thread-safe, therefore we don't need to worry about other threads being able to alter the String.

As a result, it can be shared among numerous threads that are active at the same time because, in the event that a thread modifies the value, the String pool will create a new String, keeping Strings secure during multi-threading.

Strings have the assurance that their value won't change thanks to immutability. The hash is calculated and cached at the first hashCode() call, and the same value is returned ever since. As a result, the hashCode() method is overridden in the String class to support caching.

As a result, while working with String objects, collections that use hash implementations run more quickly.


By preserving heap memory and enabling faster access to hash implementations when used with Strings, the String Pool improves speed.

Because String is the most often used data format, enhancing its performance will have a significant impact on enhancing the performance of the entire program.


No comments:

Post a Comment