What is String immutablity in Java ?
An object is considered immutable if its state cannot change after it is constructed. That means, once the constructor of an Immutable class has completed execution, the created instance cannot be altered.
String class is immutable. So, methods like toUpperCase(), toLowerCase() etc on a String object don’t modify the same object.. The modifications happen on a new object.
Let’s look at the following code for this:
String str = "Hello";
System.out.println(str);//If String was mutable, it would have printed HELLO
If you run this code, it will NOT print “HELLO”, rather it will print the original value “Hello”
This is because a new String object is created when the method toUpperCase() is called on str and that contains the uppercase string.
To make it work, use the following code that reassigns the new instance reference to the original variable.
String str = "Hello";
str = str.toUpperCase();
This program will print the uppercase string HELLO.
When the above code is executed, the VM takes the value of String str, converts to uppercase, giving us the value “HELLO”. Now, since Strings are immutable, the JVM can’t assign this value to str, so it creates a new String object, gives it the value “HELLO”, and gives it a reference str.
Why is String immutable in Java?
The exact reason for this is best known to the people who created the String class. But here are some probable reasons.. You may also read this as advantages of String immutability.
String Constant Pool
Strings are created in a special memory area in java heap known as “String Intern pool”.
While you create a new String variable(without using the String constructor, see note below), it searches the pool to check whether is it already exist. If it is exist, then return reference of the existing String object. If String is not immutable, changing the String with one reference will lead to wrong value for the other references.
Java can have a string pool because strings are immutable.
Note : Using String() constructor or any other String function like substring(), concat(), replace() etc which internally uses String() constructor always create new string constant in the pool unless we call the method intern().
String is widely used as parameter for many java classes, e.g. to obtain network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed and could lead to security issues.
Strings are implicitly thread safe because of immutability. Therefore, Strings can be shared across various different threads without the need of synchronization.
Since Strings are immutable, they can be cached and perform better compared to mutable counterparts. This is the reason why Strings are preferred as keys in hashmaps.
In a HashMap, being immutable guarantees that hashcode will always the same, so that it can be cached without worrying the changes.
String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).
Further reading :
Refer following article to understand :
- What is meant by an Immutable class in Java ?
- What is the advantage of an Immutable class ?
- How to create an Immutable class ?
- What happens when a variable or class is marked final ?
© 2017, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post