Slides Arrays Two Dimensional Arrays
Slides Arrays Two Dimensional Arrays
An array element can actually be an array. It's known as a nested array, or an array
assigned to an outer array's element.
This is how Java supports two and three dimensional arrays, of varying dimensions.
You can initialize a two-dimensional array, and define the size of the nested arrays, as
shown here.
This statement says we have an array of 3 nested arrays, and each nested array will have
three ints.
0 1 2
0 0 0 0
1 0 0 0
2 0 0 0
You can initialize a two-dimensional array, without specifying the size of the nested arrays.
Here, we're specifying only the outer array size, by specifying the length, only in the first set
of square brackets.
We've left the second set of square brackets empty.
You can also split up the brackets as shown in the second example, and you'll likely come
across this in Java code out in the wild.
When we access a one dimensional array element, we do it with square brackets, and an
index value.
So this code sets the first element in the array to 50:
To access elements in a two-dimensional array, we use two indices, so this code sets the
first element in the first array to 50.
This next code sets the second element, in the second array to 10.
The code on this slide is similar to the code we have in our class, using nested traditional
for loops.
In this case, we're not using any local variables, but accessing array elements and variables
directly.