Declaring an array of arrays is known as Multidimensional Array or Jagged Arrays. In simple words, it is an array of arrays. It is created by appending a square brackets “[]” for each dimension. Here data are stored in a tabular form that is in row-major order as shown in an example below.
Syntax:
1 2 3 4 5 | data-type name[size1][size2]...[sizeN]; or dataType[size1][size2]...[sizeN] arrayRefVar; or dataType [size1][size2]...[sizeN]arrayRefVar; |
Declaration:
1 2 | int twodim[5][10][4]; int threedim[5][10]; //data-type name[size1][size2]...[sizeN]; |
Instantiate Multidimensional Array in Java:
1 | int[][] arr=new int[3][3];//3 row and 3 column |
Array initialization:
1 2 3 4 5 6 7 8 9 | arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5; arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; arr[2][2]=9; |
We can also declare and initialize the 2D array together:
1 | int arr[][]={ {1,2,3},{4,5,6},{7,8,9} }; |
Example of a Multidimensional array in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class MultiDimensionalTest { public static void main(String args[]) { // declaring and initializing 2D array int array[][] = { {1,2,3},{4,5,6},{7,8,9} }; // Diplaying 2D Array for (int i=0; i< 3 ; i++) { for (int j=0; j < 3 ; j++) System.out.print(array[i][j] + " "); System.out.println(""); } } } |
The output of Multi-dimensional:
1 2 3 | 1 2 3 4 5 6 7 8 9 |