Search⌘ K
AI Features

Multi-dimensional Arrays

Explore the concept of multi-dimensional arrays in Java, including how to structure arrays of arrays and access individual elements with multiple indices. Understand practical examples like matrices and implement programs to calculate sums of rows and columns. This lesson helps you develop skills to work with complex array structures and apply them in real-world programming tasks.

What is a multi-dimensional array?

In Java, a multi-dimensional array is an array that contains other arrays as its values or members. The container array is termed an outer array, and the member array is termed an inner array. An array is said to be a multi-dimensional array if it has another array as its members.

Can you think of some instances where we might have been using a structure that is the same as a multi-dimensional array? One such example is a crossword puzzle!

Individual values in multi-dimensional arrays

The individual values in a multi-dimensional array are accessed through the multiple index numbers used. The following is an example of the two-dimensional array:

array1[row number][column number];

Let’s take the example of the following array:

int[][] array1 = {{10, 20, 30},
                   {16, 18, 20}};
  • The array1 is a two-dimensional array.
  • The value 20 can be accessed as array1 [1][2].
  • The number of indexes depends on the level of dimensions.

The general concepts of two-dimensional arrays, or n-dimensional arrays are implemented as follows in Java. The following program illustrates the structure of a two-dimensional array:

Java
class Test
{
public static void main(String args[])
{
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; //declaring a 2-dimensional array
for (int i = 0; i < 3; i++) // printing a 2-dimensional array
{
for (int j = 0; j < 3; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println(" ");
}
}
}

The following illustration shows the structure of the array above:

Here’s another example of the structure of a two-dimensional array:

Java
class Test
{
public static void main(String args[])
{
int[][] array = {{1, 2}, {4, 5}, {7, 8}}; //declaring a 2-dimensional array
for (int i = 0; i < 3; i++) // printing a 2-dimensional array
{
for (int j = 0; j < 2; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println(" ");
}
}
}

The following illustration shows the structure of the array above:

Here’s another example of a two-dimensional array:

Java
class Test
{
public static void main(String args[])
{
char[][] array = {{'A', 'B'}, {'C', 'D'}, {'E', 'F'}}; //declaring a 2-dimensional array
for (int i = 0; i < 3; i++) // printing a 2-dimensional array
{
for (int j = 0; j < 2; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println(" ");
}
}
}

The following illustration shows the structure of the above array.

A mathematical matrix is implemented as a two-dimensional array in Java, as shown in the following example:

matrix A=[1 ...