Arrays

Our first mutable data type.

ints, doubles, booleans, and Strings are all immutable data types.

A given value never changes.

We can compute new values from existing values but the existing values stay what they are.

For instance

int x = 1 + 2

When we added 1 and 2 and got 3 neither the 1 nor the 2 changed to 3.

Strings are also immutable

String s = "foobar";
String s2 = s.substring(1).toUpperCase()

We computed the value "OOBAR" and assigned it to s2.

But the value of s is still "foobar".

Variables can vary though

String s = 'foobar';
String s2 = s;

Clearly s and s2 have the same value.

Now we do this.

s = s.substring(1);

What do you think the values of s and s2 are now?

» s
"oobar"

s has changed.

» s2
"foobar"

s2 has not changed.

This is why it’s so important to understand the difference between values and variables.

Values exist somewhere in the computer.

Variables are names that refer to those values.

Changing what a name refers to doesn’t have any effect on the value it used to refer to.

The values of mutable data types can change

Arrays

Arrays represent a collection of values.

Each element of the collection can be independently changed.

Syntax

String[] things = { "foo", "bar", "baz" };

An array with three elements.

Index operator

[]

Operates on an array value and uses in int to select an element of the array.

Elements are like variables

Each element of an array is kind of like a variable.

  • It holds a value we can use in expressions.

  • We can assign new values to it.

Accessing elements

Given:

String[] things = { "foo", "bar", "baz" };

Then:

things[0] ⟹ "foo"
things[1] ⟹ "bar"
things[2] ⟹ "baz"

Assigning to elements

Assign to the first element of things.

things[0] = "quux";

After the assignment:

things[0]"quux"

This is mutation!

Arrays have a length property.

Note that it is a instance variable, not a method like on String.

things[things.length - 1]

I.e. the last element of the array

Mutability

Make an array and assign it to a variable.

String[] strings1 = { "foo" };

Assign the same value to a new variable.

String[] strings2 = strings1;

Now mutate the array.

strings1[0] = "baz";

Array has changed

System.out.println(strings1[0]);

Prints: baz

An array, by any other name

would be just as mutated:

System.out.println(strings2[0]);

Also prints: baz

strings2 has also changed because it's just another name for the same array.