Why are Strings Immutable in Java?
Java Strings are immutable by default. The immutability of Strings helps in providing features such as caching, security, fast performance and better memory utilization. This tutorial discusses how the immutability of Strings helps in achieving these features.
1. What is an Immutable Class?
Let us start with immutability itself. An immutable object is an object whose state is guaranteed to remain unchanged over its entire lifetime. It means that the object’s state, once initialized, can never be changed anyway.
Java also has immutable classes, which are primarily String and wrapper classes. Read more about how to create an immutable class.
Memory in Java is divided into three parts, i.e., Heap, Stack, and String Pool. The String Constant Pool is a special area used for the storage of string literals.
When we create a String, a String object is searched in the string pool with exact same content. If an existing String object is found, then its reference is pointed to the new variable, thus, effectively, the existing object is reused for the new string declaration as well. It helps in minimizing memory usage due to multiple strings with the same content.
String str1 = "value"; String str2 = "value"; String str3 = "value";
The above program creates 3 String type variables, all pointing to the same object in the spring pool area. All future Strings with content “value” will point to the same object in the heap and thus save the memory.
When we modify a string, a new string is created in the pool with modified content. The existing object is never changed.
When there is no reference variable pointing to a string object in the pool, the object is garbage collected. In this way, a string, once created, never gets changed.
3. Advantages of Immutable Strings
Let us now understand how the above-discussed immutability helps in runtime.
3.1. Application and Data Security
The first and undeniably most important reason is security. Well, it is not only about our application but even for JDK itself. Java class loading mechanism works on class names passed as parameters, then these classes are searched in the classpath.
In the following program, we are loading the SQL server driver by its class name. Imagine for a moment, Strings were mutable, then a bad actor could have changed the driver name, loaded a bad driver class in runtime and, with very little effort, hacked in the application.
public static final String DRIVER_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; Class.forName(DRIVER_CLASS);
Similarly, bad actors can change the SQL statements and perform SQL injection in runtime. Immutability ensures that such modifications never occur.
The immutability of String class gives is the basis of the string pool. Without immutability, there is no difference between a normal heap memory and a string pool.
As discussed in the previous section, string pools help achieve improved memory utilization, and, thus, better performance.
Immutable objects are automatically thread-safe in multi-threaded applications. If something can’t be changed, then even a Thread can not change it. Simple thing!
As String class is a main building block of the java programming language, because of its use in the classloading mechanism, it is mandatory to prevent the String class from being dirty in case of multiple threads. Immutability does the magic here.
The caches are generally implemented as key-value pairs, similar to Map implementation in Java. The cache keys are generally stored as Strings for quick lookups.
Consider if we could change a key after its associated value is stored in the cache. There will no possible way to retrieve the value thereafter until we build the same key accidentally.
The immutability of strings guarantees that cache keys will never get changed. That is why strings are the most used keys in caches and maps in Java.
We can conclude from the above discussion that string immutability helps in achieving the required safety and performance in a Java application.
Why Java Strings are Immutable?
Before proceeding further with the fuss of immutability, let’s just take a look into the String class and its functionality a little before coming to any conclusion. In this article, we will learn about the fact why Java Strings are Immutable.
What are Immutable objects?
Immutable objects are objects which once declared elements can’t be modified after it.
How are String Immutable?
A String in Java that is specified as immutable, as the content shared storage in a single pool to minimize creating a copy of the same value . String class and all wrapper classes in Java that include Boolean, Character, Byte, Short, Integer, Long, Float, and Double are immutable. A user is free to create immutable classes of their own.
String declaration:
This, as usual, creates a string containing “knowledge” and assigns it to reference str. Simple enough?
Let us perform some more functions:
// assigns a new reference to the // same string "knowledge" String s = str;
Let’s see how the below statement works:
This appends a string ” base” to str. But wait, how is this possible, since String objects are immutable? Well to your surprise, it is.
When the above statement is executed, the VM takes the value of String str, i.e. “knowledge” and appends ” base”, giving us the value “knowledge base”. Now, since Strings are immutable, the VM can’t assign this value to str, so it creates a new String object, gives it a value “knowledge base”, and gives it reference str.
An important point to note here is that, while the String object is immutable, its reference variable is not. So that’s why, in the above example, the reference was made to refer to a newly formed String object.
At this point in the example above, we have two String objects: the first one we created with the value “knowledge”, pointed to by s, and the second one “knowledge base”, pointed to by str. But, technically, we have three String objects, the third one being the literal “base” in the concat statement.
Why Java Strings are immutable in nature?
These are some more reasons for making String immutable in Java. These are:
- The String pool cannot be possible if String is not immutable in Java. A lot of heap space is saved by JRE. The same string variable can be referred to by more than one string variable in the pool. String interning can also not be possible if the String would not be immutable.
- If we don’t make the String immutable, it will pose a serious security threat to the application. For example, database usernames, and passwords are passed as strings to receive database connections. The socket programming host and port descriptions are also passed as strings. The String is immutable, so its value cannot be changed. If the String doesn’t remain immutable, any hacker can cause a security issue in the application by changing the reference value.
- The String is safe for multithreading because of its immutableness. Different threads can access a single “String instance”. It removes the synchronization for thread safety because we make strings thread-safe implicitly.
- Immutability gives the security of loading the correct class by Classloader. For example, suppose we have an instance where we try to load java.sql.Connection class but the changes in the referenced value to the myhacked.The connection class does unwanted things to our database.
Important Facts about String and Memory Usage
What if we didn’t have another reference s to “knowledge”? We would have lost that String. However, it still would have existed but would be considered lost due to having no references.
Look at one more example below
Example
The below programs demonstrate the immutability of Java strings.
Why String is Immutable in Java?
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Why String is immutable in Java is one of the popular interview questions. The string is one of the most used classes in any programming language. We know that String is immutable and final in Java. Java runtime maintains a String pool that makes it a special class.
Why String is immutable in Java?
Let’s look at some of the benefits of String immutability, that will help in understanding why String is immutable in Java.
- String pool is possible only because String is immutable in Java. This way Java Runtime saves a lot of heap space because different String variables can refer to the 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 in the other variables too.
- If String is not immutable then it would cause a severe security threat to the application. For example, database username, password are passed as String to get database connection and in socket programming host and port details passed as String. Since String is immutable, its value can’t be changed otherwise any hacker could change the referenced value to cause security issues in the application.
- Since String is immutable, it is safe for multithreading. A single String instance can be shared across different threads. This avoids the use of synchronization for thread safety. Strings are implicitly thread-safe.
- Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader. For example, think of an instance where you are trying to load java.sql.Connection class but the referenced value is changed to myhacked.Connection class that can do unwanted things to your database.
- 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 the key in a Map and its processing is faster than other HashMap key objects. This is why String is the most widely used 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 the Java String class and makes it special. Read this post to know how to write your own immutable class.
You can checkout more Java String examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.