• Java Data Structures Tutorial

Two Dimensional Arrays



A two dimensional array in Java is represented as an array of one dimensional arrays of the same type. Mostly, it is used to represent a table of values with rows and columns −

Int[][] myArray = {{10, 20, 30}, {11, 21, 31}, {12, 22, 32} }

In short a two-dimensional array contains one dimensional arrays as elements. It is represented with two indices where, the first index denotes the position of the array and the second index represents the position of the element with in that particular array −

Example

public class Creating2DArray {	
   public static void main(String args[]) {
      int[][] myArray = new int[3][3];	      
      myArray[0][0] = 21;
      myArray[0][1] = 22;
      myArray[0][2] = 23;
      myArray[1][0] = 24;
      myArray[1][1] = 25;
      myArray[1][2] = 26;
      myArray[2][0] = 27;
      myArray[2][1] = 28;
      myArray[2][2] = 29;      
      
      for(int i = 0; i<myArray.length; i++ ) {    	  
         for(int j = 0;j<myArray.length; j++) {
            System.out.print(myArray[i][j]+" ");
         }
         System.out.println();
      }
   }
}

Output

21 22 23 
24 25 26 
27 28 29
Advertisements