What is immutable String?
String class in java cannot be modified once created. So let us create two string objects below
</p> <p>String string1 = new String("one");</p> <p>String string2 = new String("two");</p> <p>
So once we created the above two strings, the values of these two strings cannot be modified as String class doesn’t provide any method that can allow to modify the value of a
String. In short
String class doesn’t have a
Why is String immutable in Java?
To really answer this question we will have to ask the designers of the Java language because only they can answer this questions. This was a design decision and I think a good one as Strings constitute about 20-40% of an application footprint. But what we will try to explain here is different reasons that could have led to making this choice by the language designers.
- String Intern pool exists because the Strings it holds are immutable. As the diagram below shows that two strings can refer to same one string in the intern pool. If you would modify
bwould also get modified and hence lead to unexpected behaviour
String a = "one";<br /> String b = "one";
- Strings are implicitly thread safe because of immutability. Strings can be shared across various different threads without the need of synchronization.
- Parameters are typically represented as
Stringin network connections, database connection urls, usernames/passwords etc. If they were mutable, these parameters could be easily changed. This makes an application more secure.
- String immutability also makes sure that a hashcode of a
Stringcan be cached and would always be the same. This means more efficiency as hashcode of string is used frequently.
Stringis used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).
Here is a very interesting way to change a value of a String.