A 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 = new String[] { "foo", "bar", "baz" };
An array of String
s with three elements.
Can be shortened to:
String[] things = { "foo", "bar", "baz" };
Latter syntax can only be used in a variable declaration.
new String[] { "foo", "bar", "baz" }
Use this if you want to pass an array to a method without declaring a variable: foo(new int[] { 1, 2, 3})
new String[10];
This creates an array of String
s that can hold ten elements.
The elements of the array are all set to the zero value for the type: 0
for int
, 0.0
for double
, false
, for boolean
, and null
for all reference types.
array[i]
array
is an array and i
is an int
. Refers to the i
’th element of 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!
things.length ⟹ 3
things[things.length - 1] ⟹ "baz"
Note that it is a instance variable, not a method length()
on String
s.
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 changed because it's just another name for the same array.
More technically, strings1
and strings2
are two separate variables but their value is the same, namely a reference to the same underlying array.