Two dimensional(2d) array

In programming languages which are usually learnt before java(such as C, C++), a two dimensional array is represented as a vertical stack with two partitions where each partition contains a value as below :

Two dimensional array, also referred as 2d array is visualized as a vertical arrangement where columns are arranged vertically and rows are arranged horizontally.
Elements in these arrays are accessed using index notation([][]) where first index is a row and second index represents the column count.
Each index or position in these arrays contains a value.

Example, if the above array is referenced by name sampleArray, the notation to access 7 in second row, the index will be sampleArray[1][1].

2d Array in Java
A two dimensional array in java has a bit different concept.
A multi-dimensional array in java is an array of arrays which means that each index of a 2d array contains a reference to another array which actually contains the elements.
Thus, the same 2d-array in java would be represented as :

       Two-dimensional array representation in java

Above illustration depicts that each index of the main array does not contain any value but a reference to another array.

In java, an array is an object(be it one-dimensional or multi-dimensional).
Thus a two-dimensional array of type int is an object where each index holds a reference to an int array(int []).
In other words each index points to a one-dimensional array. Second index holds the actual int values.

In above illustration, if the name of array is sampleArray, then below statements will make the concept more clear.

int value = sampleArray[1][1]; // value will be 7

int[ ]  newArray = {2, 3};  // create a new one-dimensional array

sampleArray[1] = newArray;  // assign one-dimensional array to index 1

value = sampleArray[1][1];  // value will be now 3

sampleArray[1][1] = newArray; // compiler error since index[1][1] 
                              // should contain value, not an array

int[ ] from2dArray = sampleArray[2];  // assign the array referenced by
                                      // third location to a new array

2d array declaration
A 2d array in java is declared using the below syntax:

int[ ][ ] sampleArray = new int[3][2];

The above syntax instructs the JVM to create an array referenced by name sampleArray with 3 locations and each location will point to an array of 2 elements.
Note that it is a good practice to provide both the dimensions while declaring an array but only the first dimension is necessary.
Above array can also be declared as :

int[ ][ ] sampleArray = new int[3][ ];

If we observe the array shown in illustration 2, it should have been declared as

int[ ][ ] sampleArray = new int[5][2]; or simply
int[ ][ ] sampleArray = new int[5][ ];

2d array Initialization
There are 2 ways to initialize elements of a 2d array in java.

1. At the time of declaration
Initializing array elements at the same location where it is declared as:

int[ ][ ] sampleArray = { {1, 2}, {3, 4}, {5, 6}};

There is no need to provide the size of array if it is initialized this way since the size is automatically calculated from the number of elements.
Above array contains 3 elements with each index pointing to an array of 2 elements.

2. Initializing individual elements after declaration
In this method, array is declared normally and its elements can be initialized later on as :

/* array of 3 elements with each index pointing 
 * to an array of 2 elements */
int[ ][ ] sampleArray = new sampleArray[3][2];    

/* first element of the array pointed by the 
 * first index of main array */
sampleArray[0][0] = 1;      

/* second element of the array pointed by the 
 * first index of main array */
sampleArray[0][1] = 2;

and so on…
Loop 2d array
A 2d array is an array of arrays. To iterate and print each element of a 2d array, we would require 2 loops and out of these, one loop will be inside other.

Outer loop will iterate over the entire length of  array and each element in its iteration will be an array. The inner loop will iterate over the elements of this array. Example,

int[][] 2dArray = 
  {
    {1,2,3},
    {4,5,6}
  };
// iterate over outer array
for(int i = 0; i < 2dArray.length; i++) {
  // get nested array
  int[] arr = 2dArray[i];
  // loop over inner array
  for(int j = 0; j < arr.length; j++) {
    System.out.println("Element at position[" + 
      i + "][" + j + "] is: " +arr[j]);
  }
  System.out.println("");
}

This prints

Element at position[0][0] is: 1
Element at position[0][1] is: 2
Element at position[0][2] is: 3

Element at position[1][0] is: 4
Element at position[1][1] is: 5
Element at position[1][2] is: 6

You can also use a for-each loop to iterate over a two dimensional array as shown below.

int outerPos = 0, innerPos = 0;
for(int[] arr : 2dArray) { 
  for(int val : arr) { 
    System.out.println("Element at position[" + 
      outerPos + "][" + innerPos + "] is: " + val); 
    ++innerPos;
  } 
  ++outerPos;
  System.out.println(""); 
}

As you can see, this syntax is shorter and cleaner. Two additional integer variables will only be required if you want to keep track of the position of array elements.

Let’s tweak in

  1. Though the method to access individual elements in both conventional and java arrays is same, conceptually the elements are arranged differently.
  2. A 2d array in java does not require both the dimensions at the time of declaration, only the first dimension which represents the number of rows is necessary.
    Thus, the declaration int[][] array  =new int[4][]; is valid.
  3. Array values are initialized automatically according to the type of the array in java.
    That is, all elements of an array of type int will be initialized to 0, elements of boolean type will be false and so on.
  4. Since arrays in java are objects they are created using new keyword.

Leave a Reply