How to create a two-dimensional array in Java?
To create a two-dimensional array in Java, you can use the following syntax:
int[][] array = new int[rows][columns];
This creates an array
with rows
rows and columns
columns, with all elements initialized to their default value (0
for integers).
You can also use an array literal to specify the values for the array:
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
This creates a 3x3 array with the following elements:
1 2 3
4 5 6
7 8 9
You can access the elements of the array using two indices:
int element = array[row][column];
For example, to access the element in the second row and third column of the above array, you would use array[1][2]
, which would return 6
.
Note that a two-dimensional array is actually an array of arrays, so the length of the outer array is the number of rows, and the length of each inner array is the number of columns.