Arrays with two sets of square brackets [][] are called two-dimensional arrays. A two dimensional array is used when data items are arranged in row-wise and column-wise in a tabular form. The array has two sets of square brackets [3][4], and hence it is a 2 dimensional array with 3 rows and 4 columns. This declaration informs the compiler to reserve 12 locations(3*4=12)contiguously one after the other.
Initialization of two dimensional array.
Assigning required value to a variable before processing is initialization. As we initialize a variable to the required value we can initialize the individual elements of a 2 dimensional array during initialization.
Syntex :-
data type array_name[rows][cols]={
{a1,a2,a3...an},
{b1, b2, b3...bn},
};
Example :-
int arr[2][3]={
{33, 55, 66},
{23, 33, 12},
};
Q.) Example of Multi dimensional Array.
class MultidimensionalArray {
public static void main(String[] args) {
// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
// calculate the length of each row
System.out.println("Length of row 1: " + a[0].length);
System.out.println("Length of row 2: " + a[1].length);
System.out.println("Length of row 3: " + a[2].length);
}
}
Output
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1