Our first mutable data type.
int
s, double
s, boolean
s, and
String
s 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.
int x = 1 + 2
When we added 1 and 2 and got 3 neither the 1 nor the 2 changed to 3.
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"
.
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
has changed.
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.
Arrays represent a collection of values.
Each element of the collection can be independently changed.
String[] things = { "foo", "bar", "baz" };
An array with three elements.
[]
Operates on an array value and uses in int to select an element of the array.
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.
Given:
String[] things = { "foo", "bar", "baz" };
Then:
things[0] ⟹ "foo"
things[1] ⟹ "bar"
things[2] ⟹ "baz"
Assign to the first element of things
.
things[0] = "quux";
After the assignment:
things[0]
⟹ "quux"
This is mutation!
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
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";
System.out.println(strings1[0]);
Prints: baz
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.