Multidimensional Arrays in Java - Quiz

Total: 5 questions

1. 

What is a multidimensional array in Java?

A multidimensional array in Java is an array whose elements are other arrays — an “array of arrays”. The outer array holds references to the nested arrays rather than being a single contiguous block of memory (a matrix) as in C/C++. In practice, two-dimensional arrays are used most often.

2. 

How do you declare and create a two-dimensional array in Java, and what do the left and right indices mean?

You use a separate pair of square brackets for each dimension. For example, an array of 5 rows by 4 columns is created like this:

int[][] twoD = new int[5][4];

When you access twoD[i][j], the left index i selects the row and the right index j selects the column. The first (leftmost) dimension is mandatory at creation: new int[][4] does not compile, whereas new int[4][] is valid.

3. 

How is a two-dimensional array stored in memory in Java?

A two-dimensional array variable does not point to a matrix but to an outer array of references. Each element of that array is a reference to a separate row (a one-dimensional array) that lives on the heap as its own object. Because of this, rows are stored independently, can have different lengths, and can even be null. Arrays of any dimension are stored the same way.

4. 

What is a jagged array and how do you create one?

A jagged array is a two-dimensional array whose rows have different lengths. You set only the first dimension at declaration and allocate memory for each row separately:

int[][] array = new int[4][];
array[0] = new int[1];
array[1] = new int[2];
array[2] = new int[3];
array[3] = new int[4];

Until a row is allocated, its reference is null, and accessing it throws a NullPointerException. To iterate, use array.length (the number of rows) and array[i].length (the length of a specific row) so the loop works for rows of any length.

5. 

How do you initialize a multidimensional array with values right at declaration?

If all values are known in advance, you can use an initialization block where each row is placed in its own curly braces:

double[][] arrayTwoD = {
        {0, 1, 2, 3},
        {4, 5, 6, 7},
        {8, 9, 10, 11},
        {12, 13, 14, 15}
};

The integer literals are automatically converted to double, so the array holds 0.0, 1.0, 2.0 and so on. You do not need to write new double[][] or the sizes when using this initialization form.

Page 1 of 1