Java Multidimensional Arrays

Learn Java multidimensional arrays with examples. Understand 2D arrays, 3D arrays, initialization, and accessing elements in nested arrays.

Before we learn about multidimensional arrays, make sure you know about Java arrays.

A multidimensional array is an array of arrays. Each element of a multidimensional array is an array itself. For example,

int[][] a = new int[3][4];

Here, we have created a multidimensional array named a. It is a 2-dimensional array that can hold a maximum of 12 elements.

Tip 💡: Think of a 2D array like an Excel sheet or a chessboard. row comes first, then column. matrix[row][col].

Remember, Java uses zero-based indexing; that is, indexing of arrays in Java starts with 0, not 1.

Let's take another example of a multidimensional array. This time we will create a 3-dimensional array. For example,

String[][][] data = new String[3][4][2];

Here, data is a 3d array that can hold a maximum of 24 (342) elements of type String.


1. How to initialize a 2d array in Java?

Here is how we can initialize a 2-dimensional array in Java:

int[][] a = {
    {1, 2, 3},
    {4, 5, 6, 9},
    {7},
};

How do you access the element '5' in the above array 'a'?

As we can see, each element of the multidimensional array is an array itself. And also, unlike C/C++, each row of the multidimensional array in Java can be of different lengths.

Example: 2-dimensional Array

class MultidimensionalArray {
    public static void main(String[] args) {

        // create a 2d array
        int[][] a = {
            {1, 2, 3},
            {4, 5, 6, 9},
            {7},
        };

        // calculate the length of each row
        System.out.println("Length of row 1: " + a[0].length);
        System.out.println("Length of row 2: " + a[1].length);
        System.out.println("Length of row 3: " + a[2].length);
    }
}

Output:

Length of row 1: 3
Length of row 2: 4
Length of row 3: 1

In the above example, we created a multidimensional array named a. Since each component of a multidimensional array is also an array, a[0], a[1], and a[2] are also arrays.

Here, we are using the length attribute to calculate the length of each row.


2. Iterating through 2D Arrays

Example: Print all elements of 2d array Using Loop

class MultidimensionalArray {
    public static void main(String[] args) {

        int[][] a = {
            {1, -2, 3},
            {-4, -5, 6, 9},
            {7},
        };

        for (int i = 0; i < a.length; ++i) {
            for(int j = 0; j < a[i].length; ++j) {
                System.out.println(a[i][j]);
            }
        }
    }
}

Output:

1
-2
3
-4
-5
6
9
7

We can also use the for...each loop to access elements of the multidimensional array. For example,

class MultidimensionalArray {
    public static void main(String[] args) {

        // create a 2d array
        int[][] a = {
            {1, -2, 3},
            {-4, -5, 6, 9},
            {7},
        };

        // first for...each loop access the individual array
        // inside the 2d array
        for (int[] innerArray: a) {
            // second for...each loop access each element inside the row
            for(int data: innerArray) {
                System.out.println(data);
            }
        }
    }
}

Output:

1
-2
3
-4
-5
6
9
7

In the above example, we created a 2d array named a. We then used a for loop and a for...each loop to access each element of the array.

How many loops are typically needed to iterate through all elements of a 2D array?


3. Jagged Arrays

A jagged array is an array of arrays where different rows can have different lengths.

class Main {
    public static void main(String[] args) {
        // Jagged array
        int[][] jagged = new int[3][];
        jagged[0] = new int[] {1, 2};
        jagged[1] = new int[] {3, 4, 5};
        jagged[2] = new int[] {6};

        System.out.println("Row 1 length: " + jagged[0].length); // 2
        System.out.println("Row 2 length: " + jagged[1].length); // 3
    }
}

4. How to initialize a 3d array in Java?

Let's see how we can use a 3d array in Java. We can initialize a 3d array similarly to a 2d array. For example,

// test is a 3d array
int[][][] test = {
        {
          {1, -2, 3},
          {2, 3, 4}
        },
        {
          {-4, -5, 6, 9},
          {1},
          {2, 3}
        }
};

Basically, a 3d array is an array of 2d arrays. The rows of a 3d array can also vary in length just like in a 2d array.

Example: 3-dimensional Array

class ThreeArray {
    public static void main(String[] args) {

        // create a 3d array
        int[][][] test = {
            {
              {1, -2, 3},
              {2, 3, 4}
            },
            {
              {-4, -5, 6, 9},
              {1},
              {2, 3}
            }
        };

        // for..each loop to iterate through elements of 3d array
        for (int[][] array2D: test) {
            for (int[] array1D: array2D) {
                for(int item: array1D) {
                    System.out.println(item);
                }
            }
        }
    }
}

Output:

1
-2
3
2
3
4
-4
-5
6
9
1
2
3

Key Takeaways

  • Structure: An array of arrays. int[][] is an array where each element is an int[].
  • Access: Use matrix[row][col] to access elements.
  • Ragged Arrays: Rows can have different lengths (unlike in C/C++).

Common Pitfalls

[!WARNING] Visualizing: It's easy to mix up rows and columns. Remember: First index is ROW (down), second is COLUMN (across).

[!WARNING] Uninitialized Rows: If you create int[][] a = new int[3][], the rows are null until you initialize them. Accessing them causes a NullPointerException.

Challenge

Challenge

Task:

Create a 2D array named 'matrix' with values {{10, 20}, {30, 40}} and print the element at row 1, column 1.