Multi-dimensional arrays that contain more than one index and can store information in multiple dimensions. The most common one is a two-dimensional array, also called a matrix or table. In the two-dimensional array, each element associated with two indexes. We can visualize the two-dimensional array as a spreadsheet, rectangular in shaper and containing elements that divided into columns and rows. However, Java does not indeed support multidimensional arrays. However, one can achieve the same functionality by declaring an array of arrays.
In order to understand arrays of arrays, consider an example where we want to calculate the marks obtained by 4 students of a class in 3 different subjects. An obvious way to store information is in a two-dimensional array (or matrix) which we call marks. In order to create this two dimensional array marks, we are set up much like the arrays we looked at previously but with one difference – two sets of the square brackets. The first set is for the rows and the second set is for the columns. In the code line right above the code, we informed Java that we need an array with 4 rows and 3 columns. Storing values in a multi-dimensional array require care that each row and each column is tracked.
The two-dimensional array marks of int type can be declared as follows,
int [][] marks;
The above declaration can also be written as,
int[] marks[];
int marks [][] ;
Each of the pairs of square brackets represent one dimension. This statement creates a variable marks that will refer to a two- dimensional int array.
Once you have declared an array variable, you can create an array that it will reference using the following statement,
marks = new int [4][3] ;
On execution of this statement, the JVM creates an array with 4 elements and stores a reference to this array in the variable marks. Each of these four elements is actually a reference variable referring to a (newly created) int array with 3 elements. In the two-dimensional array marks, the first index corresponds to a student and second index corresponds to a subject.
You can combine the declaration and instantiation of the above array in a single statement as follows,
int [][] marks = new int[4][3];
Once this two-dimensional array has been created, an individual element is accessed by indexing the array. Separate index must be provided for each dimension, each of which begins at 0. So in order access marks obtained by 2nd student in 3rd subject can be written as
marks[1][2] // remember arrays are 0 based
As we can calculate the length of one dimensional array using the length field. Similarly, in multidimensional arrays, we can calculate the length of each dimension. In our example, the length of the first dimension can be calculated by using the following,
marks.length
The length of the second dimension can be calculated using marks[i].length where i ranges from 0<=i<=3.
Accessing all of the items from any multi-dimensional array requires the use of a loop within a loop. Look at the code below where we use a double-loop to access all our numbers:
The complete program is as follows,
import java.util.Scanner;
public class twoDArray
{
public static void main(String[] args)
{
int[] [] a = new int[3] [2];
int i, j;
Scanner input=new Scanner(System.in);
System.out.print("Enter the Elements of 3 * 2 Matrix :");
for(i=0;i<3; i++)
{
for(j=0; j<2;j++)
a[i] [j]=input.nextInt();
}
System.out.println("Elements in Matrix from are :");
for(i=0;i<3;i++)
{
for(j=0; j<2; j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
}
}
The initial for loop is used for the rows and the second one is used for the columns. With the first loop, 0 is the value of the i variable. In the for loop, the code is another loop, and the entire double loop is executed for as long as the i variable value stays as 0. The second loop has another variable, named j and both variables, i and j, are used to access the array:
a[i][j].
We use the double loop system for looping through multi-dimensional array values, one row at a time.
Creating a Two-Dimensional Array
We can do these in three separate ways:
Using Just an Initializer
To use just an initializer to create the two-dimensional array, we use the following
syntax:
‘{‘[rowinit (‘,’ rowinit)*]’}’
rowinit has the following syntax:
‘{‘[expression (‘,’ expression)*]’}’
With this syntax, we are saying that a two-dimensional array is optional, and it is a list containing row initializers, each separated by a comma, and all in between a set of curly braces. Each of the row initializers is also an optional list, this time expressions, again with the comma separation and in between a pair of curly braces. Similar to the one-dimensional array, the expressions all have to evaluate types that are compatible.
Have a look at this example:
{{21.5, 31.6, 29.3}, {-39.7, -19.3, -17.2 }}
Using Just the New Keyword
When we use the new keyword, it allocates the memory for the array and returns the array reference. It is the syntax:
‘new’ type ‘[‘ int_expression1 ‘]’ ‘[‘int_expression2 ‘]’
We are saying that the two-dimensional array is a region of int_expr1, which are positive, row elements and int_expr2, also positive, column elements, all with the same data type. Not only that, every element has been zeroed.
Have a look at this example:
new double[2][3] // Create a two row by three column table.
Using Both Initializer and the New Keyword
Using both has a syntax approach of:
‘new’ type ‘[‘ ‘]’ [‘ ‘]’ ‘{‘[rowInit (‘,’ rowInit)*]’}’
rowInit has a syntax of:
‘{‘[expression (‘,’ expression)*]’}’
It is a combination of the syntax from the previous examples; note that there is no int_expr in between either the sets of square brackets because we can already work out how many elements are in the array just by looking at expressions list.
Have a look at this example:
new double [][] {{ 21.5, 31.6, 29.3}, {-39.7, -19.3, -17.2}}