How to define a multi-dimensional array in Java?

In Java, multi-dimensional arrays can be defined by using nested square brackets. Here are some common examples of defining multi-dimensional arrays.

  1. 2D array
int[][] array = new int[3][4];
  1. 3D array:
int[][][] array = new int[3][4][5];
  1. Irregular multidimensional arrays (also known as jagged arrays):
int[][] array = new int[3][];
array[0] = new int[4];
array[1] = new int[5];
array[2] = new int[6];

In the above example, the first bracket indicates the number of rows in the array, and the second bracket indicates the number of columns in the array. For irregular multidimensional arrays, each element may have a different number of columns, requiring separate memory allocation for each row element.

Alternatively, multi-dimensional arrays can also be defined using static initialization, as shown below:

  1. Two-dimensional array:
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
  1. Three-dimensional array:
int[][][] array = {
    {{1, 2, 3}, {4, 5, 6}},
    {{7, 8, 9}, {10, 11, 12}}
};

Please note that the elements of a multidimensional array can be of any type, not limited to primitive data types, but also including reference types.

bannerAds