Why are Strings in Java Immutable?
A String is a sequence or an array of characters. Java provides us with an immutable String class to work with strings. An immutable class is one whose instances, once created, cannot be modified.
The internal state of these objects remains the same throughout the execution of the program. We cannot update the reference to this object or its properties.
In this tutorial, we will learn why the String class is immutable in Java and its benefits.
Why are Strings Immutable?
There are a few reasons why Strings are immutable in Java. Let's take a look at these reasons.
String Pool
The String Pool is a memory location inside heap memory. The String pool stores all the strings and optimizes the memory used by the Strings. It does so by storing only a single copy for duplicate Strings. It works perfectly fine, and no inconsistencies arise because Strings are immutable.
For example, if we run the following code, str1 and str2 will point to the same String object in the String Pool. If we want to dedicate a separate space to a String, we can use the new keyword.
public static void main(String args[])
{
String str1 = "String";
String str2 = "String";
String str3 = new String("String");
}
Security
Strings are used to store sensitive information like usernames, passwords, URLs, etc. If Strings were not immutable, then anyone having access to the String reference can modify it. Immutability of Strings makes sure that we can securely use the sensitive value without worrying about someone altering it.
For example, suppose we have a method that takes a String password as input and verifies whether the password is valid or not. Now, if some hacker has access to this String, the hacker can modify the string before validation. This can lead to inconsistencies and security breaches in our application.
Multi-Threading
All immutable objects are thread-safe. Multiple threads can simultaneously access the String, as multiple read operations will not lead to any synchronization problems. Even if some thread modifies the value, an entirely new String is created without affecting the original one.
Hashcode Caching
Since Strings are immutable, it increases the overall performance of collections that use hashing to store objects.
For example, if a HashMap contains a String key, its Hashcode will always be the same as it is immutable. If the String is mutable, then the value can change after insertion. It will no longer generate the same Hashcode, and this will lead to inconsistencies.
Summary
We cannot modify immutable objects after creating them. The String class in Java is final and immutable. This makes Strings secure and thread-safe. We can freely pass Strings to methods and threads without worrying about its value being altered.
Immutability also increases the overall performance as it allows the JVM to use the String Pool and avoid storing duplicates. In this tutorial, we learned the benefits associated with immutable Strings.