Why String is Immutable or Final in Java?

In object-oriented programming, the immutable string or objects that cannot be modified once it is created. But we can only change the reference to the object. We restrict to change the object itself. The String is immutable in Java because of the security, synchronization and concurrency, caching, and class loading. This immutable nature is achieved by declaring strings as final, ensuring that once created, they cannot be modified. The reason of making string final is to destroy the immutability and to not allow others to extend it.

The String objects are cached in the String pool, and it makes the String immutable. The cached String literals are accessed by multiple clients. So, there is always a risk, where action performs by one client affects all other clients. While caching string literals in the String pool enhances performance, it also introduces the risk of unintended consequences in multi-client environments.

For example, if one client performs an action and changes the string value from Pressure to PRESSURE, all remaining clients will also read that value. For the performance reason, caching of String objects was important, so to remove that risk, we have to make the String Immutable.

Why String is Immutable or Final in Java

These are the following reasons that makes String immutable:

  • Thread Safety: Consider a scenario where multiple threads are concurrently accessing and modifying a shared string object.

Without immutability, such concurrent modifications could lead to race conditions and data corruption. By making strings immutable, Java ensures thread safety, as each thread operates on its copy of the string, preventing interference.

  • If we do not make the String immutable, it will pose a serious security threat to the application. For example, database usernames, 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 does not remain immutable, any hacker can cause a security issue in the application by changing the reference value.

String Pooling and Memory Efficiency:

Example: String literals are automatically interned in Java, allowing for string pooling.

Immutability enables the JVM to reuse existing string instances, reducing memory overhead and promoting efficient memory usage. This is particularly beneficial when dealing with large volumes of string data.

  • 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.

Security:

Example: Consider storing sensitive information like passwords as strings.

Immutability ensures that once sensitive information is assigned to a string, its value cannot be altered inadvertently. This helps mitigate security risks associated with unintentional modifications or exposure of sensitive data.

  • 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.

Performance Optimization:

Example: Performing string concatenation.

While concatenating mutable strings involves creating new string objects at each step, immutable strings allow the JVM to optimize this operation by utilizing StringBuilder internally. This leads to better performance and reduced memory consumption.

  • 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.Connection class does unwanted things to our database.

Let's understand the concept of immutable through an example.

ImmutableString.java

Output:

Why String is Immutable or Final in Java

Description: We can understand the above example with the help of the following diagram:

Why String is Immutable or Final in Java

In the string constant pool, the Hello remains unchanged, and a new string object is created with HelloWorld. It shows that the strings are immutable. The reference variable points to the Hello not to the HelloWorld.

If we want that it refers to the HelloWorld, we have to explicitly assign it to that variable. For example:

ImmutableString.java

Output:

Why String is Immutable or Final in Java

The immutability of strings, enforced by the final keyword in Java, serves as a cornerstone of the language's design. By preventing modification of string objects once created, Java ensures thread safety, promotes efficient memory usage through string pooling, enhances security, and enables performance optimizations. While it may require a shift in mindset for developers accustomed to mutable strings, embracing immutability ultimately leads to more robust and reliable Java applications.


Next TopicJava Vs Kotlin