The immutable and final nature of String class is intentional. This is by design to offer several features and advantages. In this guide, we will discuss these advantages with examples.
Reasons for String Immutability
- Security:
- Sensitive Data: Immutability feature of String offers security as data cannot be changed, this is exactly what we want for sensitive information such as password, bank details etc. This also ensures that data is safe from unintentional change due to some vulnerability.
- Thread Safety:
- Concurrent Access: Since strings are immutable, they are inherently thread-safe, this means multiple threads can access same string at the same time.
- Consistency: Since, you cannot change an immutable string. This means all threads accessing the string sees same consistent value and there is no risk of one thread changing the string while another thread is using it.
- Caching and Performance:
- String Pooling: Java uses a string pool to manage string literals. A string literal is a string created without using new keyword, for example: String str = “hello”; If a string is created with a value that is already present in the pool, then JVM returns the reference of existing string.
- HashCode Caching: Hashing provides faster operations, Immutable strings can cache their hash codes when they are created. This remains consistent as the string doesn’t change.
- Memory Efficiency:
- Shared Substrings: A string is nothing but a character array, immutable string can share their array with substrings.
- By design:
- Final Class: To make string class consistent, it is declared final. This ensures that subclasses do not alter its immutability.
- Design Principle: The string class is designed in such a way that the operations and output are straightforward and consistent.
Example of Benefits
In the following example, String str2
remains "Hello"
even after str1
is modified because strings are immutable. This demonstrates that immutability preserves the original state.
public class StringImmutabilityExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = str1;
// Concatenation resulted a new string, str1 is now
// points to this new concatenated string
str1 = str1 + " World";
// str1 now refers to a new string, but str2 remains unchanged
// because the old string "Hello" remains unchanged in memory
System.out.println("str1: " + str1); // Output: str1: Hello World
System.out.println("str2: " + str2); // Output: str2: Hello
}
}
Leave a Reply