Strings – Why Are Immutable Strings Not All Constants?

immutabilitystrings

The string type is immutable.

We can use the const keyword with strings in high level language like .NET. My understanding of 'const' means constant (it remains the same, we can't change the value).

Are strings not always constant (IMO the term constant should not be applicable in the same context if the type has to be recreated each time it means for the values life time, it was constant)?

In high level languages, specifically .NET (although I'd be interested in Java too), is this due to general memory management/tracking of objects or is there another reason?

Best Answer

You are confusing two different things:

  • Immutable means the object's memory contents cannot be modified. When you modify an immutable object (e.g, a string), the memory contents of this object are not modified. Instead:

    1. A new block of memory is allocated.
    2. The contents of the object you (tried to) modify is copied to this new block, with the part you wanted to change is changed in this new block.
    3. The pointer (i.e, the reference) is assigned to this new block.
  • Constant means the variable cannot be modified at compile-time. Whether a string or an integer the contents of the variable (or what it points to) cannot be changed or assigned at compile time.

Related Topic