The string is Immutable in Java: In this post, we are going to understand another important concept. That is why string is immutable in java? It’s a very popular interview question because the string is one of the most used classes in Java programming language.
An immutable class is a class whose instances cannot be modified, and the instances are initialized when the instance is created. You can not change or alter the information of an immutable class.
We have discussed in our previous posts that string class objects are immutable and final in Java programming language, and we have already discussed the feature of string constant pool, which makes String more special classes.
Why is String immutable in Java?
Let’s go through with the benefits of String Immutability, which helps you understand why the string is immutable in Java?
- String pool is possible only because the string is immutable. As we already shared that because of string constant pool concept when a user creates a new string object, then JVM first checks in string pool for the literal, and if it found the literal in string constant pool, then it creates a reference, not a new object. In this process, Java runtime saves a lot of space in the Heap memory area.
As multiple objects reference to one literal, so because String is immutable, it does not affect other objects; otherwise, if one object changes the value of literal, then it reflects others.
- The string is widely used as a parameter for many java classes like database username, password, database connection, and also in socket programming. As String is immutable other users are not able to able to change the value. In that way, the security of the application is increased.
- Hashcode of a string is used frequently in Java programming language. In Map or Set, the hashcode is used more regularly, but as the string is immutable, so there is no need to worry about the changes and the hashcode always, the value will be the same. So there is no need to calculate the hashcode every time.
We have noted down some of the important reasons which are only possible because of the String immutable. If you found anything wrong or you want to add something in the above post, then you can comment in the comment section