why string is immutable in java

What is immutable String?

String class in java cannot be modified once created.  So let us create two string objects below


String string1 = new String("one");

String string2 = new String("two");

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 setValue(String) method.

 

Why is String immutable in Java?

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.

  1. 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 a then b would also get modified and hence lead to unexpected behaviour
    String a = "one";
    String b = "one";

  2.  Strings are implicitly thread safe because of immutability. Strings can be shared across various different threads without the need of synchronization.
  3.  Parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If they were mutable, these parameters could be easily changed. This makes an application more secure.
  4.  String immutability also makes sure that a hashcode of a  String can be cached and would always be the same. This means more efficiency as hashcode of string is used frequently.
  5. String is 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.

References

http://stackoverflow.com/questions/22397861/why-is-string-immutable-in-java

Like this post? Don’t forget to share it!

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *