05.0 Java Notes‎ > ‎

Java: 2D Arrays

  • 2-D arrays extend the concepts of array to a second dimension.  
  • The is no practical limit on the number of dimensions an array can have; 3-D, 4-D, 12-D etc.
Creating 2D Arrays in Java

Either one of the following two coding techniques will create an array that will hold 150 integers -- 10 rows of 15 integers each.

// declares the array

int[][] n;  


// initializes the array

n = new int[10][15];  

//declare and initialize in one line


int[][] n= new int[10][15]; 



Either one of the following two coding techniques will create an array that will hold 200 Cells.  A Cell would be some type of user defined class

Cell[][] universe;

universe = new Cell[10][20];

Cell[][] universe= new Cell[10][20];



you can have an array of any data type, including an array of a class you create!



Assign Values in a 2-DArray

The following code will place 150 random integers from 0 to 99 into the array n

for(int row=0;row<10;row++){

    for(int col =0; col <15; col++){

    n[row][col]= (int)(Math.random()*100);

    }

}


in this case the row and col is used as the indices of the array and the counter for the for loop's


The following code will create 200 cells into the array universe

for(int row=0;row<10;row++){

    for(int col =0; col <15; col++){

    universe[row][col]= new Cell(row,col);

    }

}


in this case the row and col is used as:

  • the indices of the array 
  • the counter for the for loop's 
  • parameters for the cell's constructor -- this way the cell knows it own location in the universe.

Comments