Why String is immutable in java is one of the popular interview question. String is one of the most used classes in any programming language. We know that String is immutable and final in java and java run-time maintains a String pool that makes it a special class.
Why String is immutable in Java?
Let’s look at some benefits of String immutability, that will help in understanding why String is immutable in java.
String is immutable for several reasons, here is a summary:
- Security: parameters are typically represented as
Stringin network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
- Design:- String pool is possible only because String is immutable in java, this way Java Runtime saves a lot of java heap space because different String variables can refer to same String variable in the pool. If String would not have been immutable, then String interning would not have been possible because if any variable would have changed the value, it would have been reflected to other variables also.
- Thread Safe:- Since String is immutable, it is safe for multithreading and a single String instance can be shared across different threads. This avoid the usage of synchronization for thread safety, Strings are implicitly thread safe
- Caching:- Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys. Above are some of the reasons I could think of that shows benefits of String immutability. It’s a great feature of Java String class and makes it special.
- Class loading:
Stringis used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state). Had String been mutable, a request to load “java.io.Writer” could have been changed to load “mil.hacker.DiskErasingWriter”
That being said, immutability of
String only means you cannot change it using its public API. You can in fact bypass the normal API using reflection.
For Example set value of Private field using Reflection API.
Field privateField = Class.forName("org.example.transittime.MyClass").getDeclaredField("privateString");
MyClass objTest = new MyClass();
System.out.println(privateField.get(objTest)); // prints "default string"
privateField.set(objTest, "private string updated");
System.out.println(privateField.get(objTest)); //prints "private string updated"