Multidimensional Array in Java
In Java, a multidimensional array is an array of arrays. It is used to represent tables or matrices consisting of rows and columns.
The syntax to create a multidimensional array is as follows:
cssdatatype[][] arrayname = new datatype[rows][columns];
For example, to create a 2-dimensional array of integers with 3 rows and 4 columns, you would use the following code:
cssint[][] myArray = new int[3][4];
You can also initialize the array with specific values using curly braces. For example:
cssint[][] myArray = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
You can access an element in a multidimensional array by specifying its row and column index. For example, to access the element in the second row and third column of myArray
, you would use the following code:
cssint element = myArray[1][2];
You can also iterate over a multidimensional array using nested loops. For example, to print all the elements of myArray
, you would use the following code:
cssfor(int i=0;i<myArray.length;i++) {
for(int j=0;j<myArray[i].length;j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
This code will print the elements of the array in row-major order.
Comments
Post a Comment