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:

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:

The previous code creates an array like the following, where array[0] and array[1] are themselves object references of the type int[]:

Multi-dimensional Array Example

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:

Apart from the basic syntax, you can also both create and initialize a multi-dimensional array at once, using the shortcut syntax:

The anonymous creation syntax is also valid:

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.

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.

Leave a Reply