A mutable object can be changed after it's created, and an immutable object can't.
In Java, everything (except for strings) is mutable by default:
There's no way to make existing objects immutable. Even if an object is declared final, its fields can still be changed:
That said, if you're defining your own class, you can make its objects immutable by making all fields final and private.
Strings can be mutable or immutable depending on the language.
Strings are immutable in Java.
Any time you change a string (e.g.: tacking on an extra character, making it lowercase, swapping two characters), you're actually creating a new and separate copy:
But in some other languages, like C++, strings can be mutable, and we can modify them directly:
If you want mutable strings in Java, you can use a StringBuilder object:
Or, you can convert the string to an array of characters, which will be mutable.
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.
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!