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 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.