Academic Java    Java Tutorial  >  Arrays  >  multidimensional arrays (a)

multidimensional arrays Example

An element of an array may itself be an array.

Each element of which may itself be an array. And so on. Arrays of this form can be thought of as multidimensional.

Arrays can have more than one dimension, in fact any number.

A convenient notation allows us to create and manipulate multidimensional arrays, as shown in this program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// MultiDimensional Arrays Example
class MultiDimensionalArraysExample {

   public static void main(String[] args) {

      int[][] ia = { {8,3,9}, {-16,4}, {12,18,15}};

      int i = ia[0][1];

      i = ia[2][2];

      int[] ib = ia[1];

      ia=null; ib = null;

      int[][][] ic = {{{6,7},{8}},{{4,5}},{{12,15,18},{23,55},{7}}};

      i = ic[2][1][1];

      ib = ic[2][1];

      ia = ic[0];
   }
}

6 A 2-dimensional array is initialized (the number of matching square brackets indicates the dimensionality). The syntax to the right shows initialization values in braces.
The first element of ia is an array of 3 elements. The second an array of 2, and the third an array of 3 elements.

8 The righthand side of this initialization of the variable i shows how an element of a 2-dimensional array is indexed. The index of each dimension is in brackets. i now contains the value 3.

10 The variable i is assigned to from another element. i now contains the value 15.

12 The one-dimensional array ib is assigned not an individual int element of ia but the one-dimensional array held in element index 1 of ia. ib now contains {-16,4}

16 Here is a 3-dimensional array being initialized. The dimensionality is expressed with the matching pairs of brackets.

18 An element is accessed and assigned to the int variable i. i now contains the value 55.

20 An element of the second dimension (an int[]) is assigned to ib. ib now contains {23,55}.

22 Finally, an element of the first dimension (an int[][]) is assigned to ia. ia now contains {{6,7},{8}}.