A mutable object can be changed after it's created, and an immutable object can't.
For example, let's look at lists and tuples in Python. Lists are mutable and tuples are immutable:
Different languages have different policies on whether strings should be mutable. Ruby has mutable strings:
But strings are immutable in Python:
In C++ and C, strings can either be mutable or immutable, depending on whether the string is declared with the const modifier:
In Swift, strings can either be mutable or immutable, depending on whether the string is declared with the var keyword:
Technically, PHP strings are mutable—you can treat them as an array of characters (like in C) and modify them. However, the preferred practice is to treat them as immutable, and there is at least one very strong reason for it - if you dereference the array elements directly, you're in a big mess if you actually have a multi-byte (Unicode) string.
Mutable objects are nice because you can make changes "in-place," without allocating a new object. But be careful—whenever you make an in-place change to an object, all references to that object will now reflect the change (whether you like it or not)!
Pass Your Interviews with My FREE 7-Day Crash Course
I'll teach you the right way of thinking for breaking down tricky algorithmic coding interview questions you've never seen before.
No prior computer science training necessary—I'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe if you hate it.