Understanding the Immutability of Strings in Java

Chunks
3 min readJul 11, 2023

Everybody talks about how Strings are immutable and how this decision to make Strings immutable has become one of the best things to happen to Java Strings.

In this article, we will understand what immutability is and why Java as a programming language decided to make Strings immutable.

What is a Mutable Object?

From Merriam-Webster Dictionary, Mutable is something capable of being changed. With this definition in mind, a mutable Object is an object whose internal state can be changed.

When Objects are created in Java, the state and fields are stored in the Java Heap. The state and field values can be changed if it is a mutable object.

public class Person {
public int age = 45;
public long phone = 123456;
}

In the code snippet shown above, the fields (age and phone) that make up the Person object can be changed by another code block and this change would change whatever existed in Java Heap. If the age is changed to 55, it replaces the reference in the memory-there won’t be any object with age 45 in the memory again.

What is an Immutable Object?

An Immutable object is the opposite of a Mutable object discussed in the previous section. It’s an Object whose internal state cannot be changed after construction. Java String class is a perfect example of an immutable object.

 String hello = "Hello";
hello = hello.replace("Hello", "Hello World");

Looking at the snippet above, we may think that the String class is mutable since it looks like we are changing the state from “Hello” to “Hello World” and one should expect only “Hello World” in memory. In the actual sense, this is not how it works with String.

Internally, every unique string literal in Java is stored in String Constant Pool (SCP). So in this context, “Hello” is a different entity while “Hello World” is also a different entity or object in the SCP-the latter does not replace the former in memory, unlike mutable objects.

Why are Strings Immutable?

Caching

Arguably, String is the most widely used data structure in Java. With this wide usage, it would only make sense to cache some of the initialization in memory so that they can be reused. Without immutability, it would be difficult to achieve caching as every string initialization would result in a new object in memory thereby using up a lot of memory.

   for (Customer customer : customers) {
String firstName = customer.getFirstName();
String email = customer.getEmail();
emailCustomer(firstName, email);
}

From the snippet above, Imagine that you have a thousand customers you wish to email given their first name and email address, 30% of these customers have the same first name (e.g. John). If String was not immutable, the line String firstName = customer.getFirstName() would create 300 instances/objects (30% of 1000) in memory with the name “John”.

With Immutability and String Pool, there will only be an instance of String “John” in memory which can be reused. This improves performance on a larger scale.

On the other hand, any String created with the “new” keyword (String str = new String(“John”), creates a new Object in memory.

String Pool Caching

Security

If Strings are not immutable, it poses a critical security threat in applications. For example, Database credentials, usernames, and passwords are mostly passed as strings in applications, if Strings are not immutable, their internal state could be changed and a hacker could take advantage of that.

 private void creditCustomer(String customerUsername) {
//Run validations

//Call Payment System to transfer
callPaymentSystem(customerUsername);
}

The caller of the method in the code snippet above has the reference of customerUsername. If Strings are mutable, whoever has the reference(e.g. hacker) can change the internal state from the original username to whatever username that the hacker wants.

Thread Safety

Because of the Imuutablity of Strings, multiple threads can access a single String instance without any form of internal corruption to the state of the object. Strings are safe for multi-threading as they are thread-safe implicitly.

Conclusion

We have learned what Immutable Objects are and why Strings are Immutable.

--

--