Declaring Multi-Dimensional Arrays
Multi-Dimensional arrays are arrays whose elements are themselves arrays. The same as One-Dimensional arrays there are different ways of declaring them. Only one of these ways is the preferred way, but for the purpose of the exam you must know all the valid ways. Let’s see them with some examples:
1 2 3 4 5 6 7 8 9 10 11 |
// Declaring a 2-dimensional array int[][] array; // Preferred way int[] array[]; // Valid but discouraged // Declaring a 3-dimensional array int[][][] array; // Preferred way int[] array[][]; // Valid but discouraged int[][] array[]; // Valid but discouraged |
Creating and Initializing Multi-Dimensional Arrays
Once you have a multi-dimensional array variable, you can create the array (i.e. allocate memory for the array elements) and assign values to its elements using the basic syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// creating the array array = new int[3][3]; // initializing the array (element 0 = first "row") array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; // initializing the array (element 1 = second "row") array[1][0] = 4; array[1][1] = 5; |
The previous code creates an array like the following, where array[0]
and array[1]
are themselves object references of the type int[]
:
Notice that when declaring this kind of arrays, the length of the dimensions after the first one can be left unspecified if none of the dimensions are specified after it:
1 2 3 4 5 6 7 8 |
// 2-dimensional array array = new int[3][]; // 3-dimensional array array = new int[3][][]; array = new int[3][4][]; |
Apart from the basic syntax, you can also both create and initialize a multi-dimensional array at once, using the shortcut syntax:
1 2 3 |
int[][] array = { {1, 2, 3}, {4, 5} }; |
The anonymous creation syntax is also valid:
1 2 3 |
new int[][] { {1, 2, 3}, {4, 5} }; |
Dimension Evaluation
A final and important note about multi-dimensional arrays. In order to access any multi-dimensional array element, you must specify its indexes by giving the dimension expressions (e.g.array[i+1][j+2]
). You must know that each dimension expression is always fully evaluated before any dimension expression to its right. If evaluation of a dimension expression fails, no part of any dimension expression to its right will be evaluated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
int array[][][] = new int[2][2][2]; int i = 0; try { int element = array[2][++i][0]; } catch (ArrayIndexOutOfBoundsException ex) { ex.printStackTrace(); } finally { System.out.println(i); } |
This code creates an array of 2x2x2 elements and then tries to access an array element where the first dimension index is 2
(out of bounds). This dimension evaluation fails and so no other dimensions are evaluated. The final output of the code is 0
because ++i
is never executed.