Two Dimensional Arrays (Array of Arrays)


Two Dimensional Arrays (Array of Arrays)

To inform the compiler that it is a two dimensional array, place two pairs of square braces either as prefix or suffix to array object. We can place any number of one dimensional arrays in a two dimensional array. A C/C++ programmer is much aware of "a two dimensional array is an array of one dimensional arrays", (Array of Arrays).

Creation, Assignment and Accessing two dimensional arrays

Following ArrayTest3 is an example of a two-dimensional array. A marks array object is created and elements are assigned later.

public class ArrayTest3
{
  public static void main(String args[])
  {
    double marks[][] = new double[3][4];

    System.out.println("Rows count: " + marks.length);
    System.out.println("Elements of 1st row: " + marks[0].length);
    System.out.println("Default value: " + marks[0][0]);
					// 1st row values
    marks[0][0] = 45.9;
    marks[0][1] = 55.9;	
    marks[0][2] = 65.9;	
    marks[0][3] = 75.9;
					// 2nd row values
    marks[1][0] = 45.4;
    marks[1][1] = 55.4;	
    marks[1][2] = 65.4;	
    marks[1][3] = 75.4;
					// 3rd row values
    marks[2][0] = 45.2;
    marks[2][1] = 55.2;	
    marks[2][2] = 65.2;	
    marks[2][3] = 75.2;

    System.out.println("1st element value: " + marks[0][0]);
    System.out.println("\nPrinting in matrix form");
    for(int i = 0; i < marks.length; i++)   
    {
       for(int j = 0; j < marks[i].length; j++)  
       {
	  System.out.print(marks[i][j] + "\t");
       }
       System.out.println();        // just to give a new line
    }
  }
}  
Two Dimensional Arrays (Array of Arrays)
Output screen of ArrayTest3.java

double marks[][] = new double[3][4];

The above statement creates a two-dimensional array object marks that can store 12 elements of double data type, matrixed in 3 rows and 4 columns. Being double, the default value assigned for all the 12 elements is 0.0.

Following is the schematic representation of the task of the above program.

  1. marks.length gives the number of rows present in the two-dimensional array.
  2. marks[0].length gives the number of elements present in the first row. Ofcourse, it is the same for all the rows; but differs in the later program.
  3. There is no predefined way to find the total number of elements present in a two-dimensional array.
  4. marks[0][0] returns the element existing in the first row and first column.

5 thoughts on “Two Dimensional Arrays (Array of Arrays)”

Leave a Comment

Your email address will not be published.