Java Immutability – When and Why to Use Immutable Pointees

immutabilityjava

In Java, the String object is both immutable and also a pointee (aka reference type). I'm sure there are other types/objects which are both immutable and a pointee as well and that this extends further than just Java.

I can not think where this would be desirable possibly due to my own experience I've only used either reference types OR immutable primitive types.

Can some one please give me a situation where it would be useful so I can get an appreciation for their meaning/value/concept.

Best Answer

An immutable reference type behaves similarly to a value type.

If String were not immutable, something like this could happen:

String a = "abc";
String b = a;
a.ReplaceCharAt(1, "X");  // this is not possible, if the type is immutable

// b is now "aXc", which might be counter-intuitive

Immutability prevents this from happening: Whenever I assign a string to a variable, I can be sure that this string won't change until I reassign the variable.

On the other hand, we still get the benefits of reference types for String:

  • In the example above, abc would only be stored once in memory.
  • Strings can be variable in size.

The latter one is probably the main reason why Strings are reference types in Java and .NET. Often, value types are stored on the stack. To put something on the stack, the compiler needs to know its size beforehand, which is kind of difficult for strings of varying size.

Related Topic