Why are Strings immutable in java?

Modified on Tue, 28 Mar, 2023 at 3:52 PM

In Java, strings are immutable, which means that once a string object is created, its value cannot be changed. This is because the String class is designed to be thread-safe and can be shared across multiple threads without any synchronization issues. Additionally, immutability provides several other benefits such as security, caching, and ease of use.

Here is an example to illustrate why strings are immutable in Java:

In this example, we create a string variable str1 and initialize it to the value "Hello". We then create another string variable str2 and assign it the value of str1. Next, we concatenate the string " World" to str1 and reassign the result back to str1. Finally, we print the values of both str1 and str2.

This shows that although we modified the value of str1, the value of str2 remained unchanged. This is because when we assigned str2 to the value of str1, it created a copy of the reference to the original string object. When we modified str1 by concatenating " World" to it, it created a new string object with the value "Hello World" and assigned the reference to that new object to str1. This did not affect the value of str2, which still points to the original string object with the value "Hello". This demonstrates the immutability of strings in Java.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article