This question has been asked in a number of interviews in the past and is still being asked. If you search google for this question you will find people trying to answer this question. But no one has been able to answer it properly and no one except the Java designers can really answer.
We will try to find out what aspects of Java does String immutability affect. So let us look at various affects String immutability has:
- String Intern pool exists because the Strings it holds are immutable.
- Strings are implicitly thread safe because of immutability.
- Parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc.
- Efficient hashcode for String as it can be cached
- String is used as arguments for class loading. If it was mutable then classloader would have to create its own local copy to make sure that the string doesn’t change after the argument is passed.
Here are the resources that I have referred to make the above answer and you can also refer to them to find what others have to say about this question.
2 thoughts on “Why is String immutable in java?”
Why hashcode will be cached?