Java Multi Dimensional Arrays in Detail with Program Example

In this Java Programming tutorial we will study and understand the concept of Java Multi Dimensional Arrays in detail and also see a few program examples. Before we start off with this topic make sure the concept of Java Arrays is clear. Check this Article of you want to know more about java arrays.

Java Multi Dimensional Arrays are basically array of arrays. A multidimensional array is a nested array; an array-within-an-array. For simplicity purpose lets consider a 2-Dimensional array(although there can be more than 2 dimensions).

We can imagine a 2-Dimensional array (2D) as a table of values, or a matrix. There are rows and columns within the table/matrix. These are also known as Jagged Arrays. A multidimensional array is created by appending one set of square brackets ([ ]) per dimension.

Examples:

int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array

Lets see a Program example of 2-D array and then we will try to understand the program

2-D Array in Java Example Program
class multiDimensional
{
    public static void main(String args[])
    {
        // declaring and initializing 2D array
        int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
 
        // printing 2D array
        for (int i=0; i< 3 ; i++)
        {
            for (int j=0; j < 3 ; j++)
                System.out.print(arr[i][j] + " ");
 
            System.out.println();
        }
    }
}
Output
2 7 9
3 6 1
7 4 2
Program Explanation –

As you can see in the above example we have created a 2-D array and initialized it with values. Here’s how the visual representation looks like –

multi-dimensional arrays java

As you can see, the array locations in the first ellipse points to another set of arrays, thus known as array of arrays. Similarly, a 3-D array will have one more set of array attached ahead of the yellow arrays as shown in the diagram.

Watch it on YouTube

One thought on “Java Multi Dimensional Arrays in Detail with Program Example

Leave a Reply

Your email address will not be published. Required fields are marked *