Skip Top Navigation Bar

Mutable vs Immutable Data

Mutable Data

Some examples of mutable data:

Immutable Data

Now, let's discuss immutable data. There are times we would not want data to change during the running of a program. We store data that isn't supposed to change in an immutable data type.

Some examples of immutable data:

  • A physical address. This is different from an address that has been assigned to a person. A person can change their address, but the old address will still exist. It will likely become someone's new address. But the physical location will not change.
  • A vehicle's VIN number, make, model, year it was built. Some data about a vehicle that would be mutable: how much gas is in the gas tank, the number of miles on the car, the owner of the vehicle, the license plate.
  • The data stored in a database, for example, one that stores the data meteorite landing. It included the name of the meteorites, the date, the mass, the geolocation of the landing. None of this data can change during the analysis of the data.

Immutable String Objects

There are classes where the data is immutable. For example, the String class. When you create a String, it is immutable. Once we start working with String data, we will see that we are unable to change the value of a String object. We can assign a String variable to a new String that is an adapation of the original value.

For example, consider a database of students with information about a student:

  • their name,
  • address,
  • parent contact information,
  • course history, and
  • grades.

For this example, let's say the name variable holds the student's first and last name:

String name = "Jane Johnson";

If this student would need their name changed to include their middle name as well, there is no way to modify the current value "Jane Johnson" to a new value. The variable name would need to be assigned the new value, such as:

String name = "Jane Java Johnson";

As a teacher, perhaps you want to print name tags with just the student's first name. Since String data is immutable, we are not able to modify "Jane Java Johnson" to be "Jane". We will be able to access a part of a String object; however in doing so, we create a new String value that is part of the String. We would then assign the result to a varaible.

Resources

Next Learn Tutorial

Learn: Introduction to Records