Multidimensional Array

Learn how to create 2D or 3D array


Multi-Dimension array has multiple array in single array. Simplest example of multidimension array is 2D array, in which every element is specified using two indices. 2D array are useful in storing matrix. Java has capacity to craete array with multiple dimension in a single array.

Two dimension Array Declaration

<Type> [][] var1;
    Or
<Type>  var1[][];

Create Multi-Dimension Array

For allocating memory to multidimension array, new keyword is used. If array is initialised in same statement of declaration then there is no need of new keyword.

// Creating 2D array
int [][]a=new int[2][2];

// Creation & Initialisation of 2D array
  int [][]a={{1,2,3},{5,6,7}};
  

Above statement will create an 2D array of two rows and three columns.





Program to store matrix

 //file:matrix.java
 // www.jgyan.com
 class matrix
  {
    public static void main(String arg[])
	 {
	   int a[][]={{2,3,4},{0,-1,8},{4,5,6}};
	   int i,j;
	   for( i=0;i<3;i++)
	    {
		  for(j=0;j<3;j++)
		  System.out.print(a[i][j]+" ");
		  System.out.println();
		 }
	 }
  }
  /*Output:
  2  3 4
  0 -1 8
  4  5 6
  */
	

Asymmetric array in java

Java support multidimension array with different capacity. For example a[3][3] denote an 2D array with 3 rows and 3 column. In java multidimension array can be created with different column size.

 //file:matrix1.java
 //www.jgyan.com
 class matrix1
  {
    public static void main(String arg[])
	 {
	   int a[3][];
	   // Creating three array with different capacity
	   a[0]=new int[3];
	   a[1]=new int[5];
	   a[2]=new int[2];
	   
	   a[0][0]=12;
	   a[0][1]=2;
	   a[0][2]=4;
	   
	   a[1][0]=1;
	   a[1][1]=23;
	   a[1][2]=15;
	   a[1][3]=16;
	   a[1][4]=56;
	   
	   a[2][0]=21;
	   a[2][1]=45;
	   
	   int i,j;
	   for( i=0;i<3;i++)
	   System.out.print(a[0][i]+" ");
	   System.out.println();
	   
	   for( i=0;i<5;i++)
	   System.out.print(a[1][i]+" ");
	   
	   for( i=0;i<2;i++)
	   System.out.print(a[2][i]+" ");
		 
	 }
  }
  /*Output:
12 2 4 
1 23 15 16 56
21 45 
  */