Incremental Java
Strings Are Immutable

Immutability

For many objects, you can construct it, and change its contents. For example, you might have a ShoppingCart object. You might add some carrots, ice cream, and cereal to the cart. This changes the contents of the cart.

If an object can change its contents, it is said to be mutable. Mutable is just a fancy word for "able to be changed".

Sometimes, objects can't change, once constructed. String objects can't change, once constructed. They are immutable. Immutability is sometimes a very nice property for an object to have.

Why?

Suppose you have a handle to a String object. Then, the handle gets copied. And maybe it gets copied again. Suppose the String object is "cat". If it's immutable, you can be sure, later on, that it's still "cat". If it were mutable, then maybe someone else would come along and change it to "slimedog", and you'd never even notice until you checked it.

Substring

Although we won't get into the details of it now, String has ways to extract substrings. For example, suppose you have the string, "slimedog". You can extract out "dog" or "slime" or even "medo". You can extract out one or more consecutive letters from the original string.

This leaves the original string unchanged. When you extract out the substring, "slime", Java creates a new string. It didn't do anything to the old string because Java says strings are immutable.

As you learn about other classes in Java, see if they are immutable. Most classes are not, but a few are. You'll eventually begin to appreciate why immutability can be a very useful property.