Java

Why String Is Immutable In Java?

In Java, we have mutable variables and immutable variables. Mutable variables are those variables whose values may vary but the values of immutable variables remain unchanged. As we all know that the values of a variable vary which means that the values of a variable can be changed according to the requirement so that the reference to a value is also changed. But think what happens if this will happen in a very serious security-related java code? That will be a disaster. But there is a data type that’s value will not change if it is declared.

In this write-up, we will see

  • What is String immutability in Java?
  • What is the reason that String is immutable in Java?

What is String immutability in Java?

In Java, a string is said to be immutable when a value is assigned to a string for the first time it will not change at any cost in the future, if we try to change the string value in the future it will create a new object with our required value but does not change the original value? This concept is known as string immutability.

Let’s understand it

Code:

public class arry {
    public static void main(String[] args) {
        String k = "immutability";
        k.toUpperCase();
        System.out.println(k);
    }
}

In the above code, we create a string type variable with a value immutability. Then we use a string method with k to convert the string value into upper case letters. Lastly, we display the value of k.

Output:

The above output shows that we try to change the value of k by converting it into upper case letters but due to string immutability the original value remains the same and is displayed as an output.

What is the reason that String is immutable in Java?

In Java, strings are said to be immutable because the change in the value of the variable affects the working of all the reference variables pointing to that object. String immutability also helps in enhancing the program’s security, performance, speed, cashing, concurrency and synchronization. Due to string immutability, a lot is spaced in the heap memory of JVM (Java Virtual Machine).

Conclusion

In Java, Strings are immutable because it avoids the change in the value of the variable that may affect all the reference variables pointing to that object. In this article, we have talked about the string immutability and the reason behind its immutability as well as the benefits of the string immutability.

About the author

Muhammad Huzaifa

I am a computer science graduate with a passion to learn technical knowledge and share it
with the world. I love to work on top state-of-the-art computing languages. My aim is to best
serve the community with my work.