Chapter 2 |
Multidimensional arrays
One-dimensional arrays are good at storing linear collections of elements. Two-dimensional arrays can be used to store a matrix or a table.
The syntax for declaring a two-dimensional array is:
data_type[][] arrayName; data_type arrayName[][];
An example of creating a two-dimensional array of 5-by-6 int values and assign to variable myArray is:
int[][] myArray = new int[5][6];
To assign the value 10 to a specific element at row 2 and column 3, use:
myArray[2][3] = 10;
To use array initializer to declare, create and initialize a two-dimensional array, use:
int[][] myArray = { {1,2,3}, {4,5,6}, {7,8,9} };
To get the length of each element, we can write:
for (int i = 0; i<myArray.length; i++){ int len = myArray[i].length; System.out.println(len); }
Analogically, it is possible to create arrays that have even more dimensions.
Chapter 2 |