Immutable

Explanation of the term immutable
When you say something is immutable ( e.g. strings are immutable ) what does this actually mean ? It simply means once the value of the variable has been set, it cannot be changed. It’s not the value of the string that cannot be changed but the memory location.
Consider the example below:

immutable1

I have a simple loop structure which iterates 3 times. On each iteration, the text “loop” is appended to the variable str. What actually happens is this:

Loop 1
String object created on the heap with value set to “loop”. Memory address = 0x111. Reference to heap object passed back to str reference variable

Loop 2
New string object created on the heap with value set to “looploop”. Memory address = 0x222. str reference variable updated to point to memory location 0x222
Object at 0x111 now a candidate for garbage collection

Loop 3
New string object created on the heap with value set to “looplooploop”. Memory address = 0x333. str reference variable updated to point to memory location 0x333
Object at 0x222 now a candidate for garbage collection

Posted in Uncategorized

Leave a comment

Design a site like this with WordPress.com
Get started