(Im)Mutable

Mutable and immutable are common English words. Something that can be changed is mutable and that cannot be is immutable. I came across these few years ago but it was an over-head-flow then. There are two classes in Java String and StringBuilder and both suffice almost the same purpose with some additional features in the latter. So I explored the difference in terms of their performance and genesis and came across these keywords.

The meanings of these words are similar in other programming languages. Here I will take the instance of Java only. So coming to the class String, it is immutable and the StringBuilder is mutable.

Considering the mutable objects, their content can be changed post construction. Performing any manipulation on the mutable object will over-write the content in the object initially created. Note no new object is created as most of us normally expect. Let us create a StringBuilder like:

StringBuilder sb = new StringBuilder();
sb.append("Kamalpreet");
sb.append("Kaur");
sb.append("Grewal");

In the memory heap, this will be only one object looking like:

The reference to the StringBuilder points to the same object. However such is not the case for immutable objects like String. Let us create like below:

String s = "Kamalpreet";
s.concat("Kaur");
s = s.concat("Grewal");

Due to immutable behavior of String class, the new results will be stored in a new object. Note the third line in the code above. If the assignment is not done, the reference will continue to point to the initial string with value Kamalpreet.

This all applies to all other mutable and immutable objects in different programming languages.

Leave a Reply

Follow

Get notified with the latest posts

Plugin Supporter WordPress Post Navigation
%d bloggers like this: