Similar to a 1-D array, a 2-D array is a collection of data cells. 2-D arrays work in the same way as 1-D arrays in most ways; however, unlike 1-D arrays, they allow you to specify both a column index and a row index.
All the data in a 2D array is of the same type.
Similar to the 1-D array, we must specify the data type, the name, and the size of the array. The size of a 2-D array is declared by the number of rows and number of columns. For example:
class Testarray{public static void main(String args[]){int number_of_rows=6;int number_of_columns=5;int arr[][] = new int[number_of_rows][number_of_columns];}}
In the example above, arr
is the name of the array.
The total number of elements in this 2-D array is:
number_of_rows * number_of_columns
So the total number elements in arr are 30.
You can also initialize an array while declaring it in the following manner:
// initializing an array on declarationint arr[][] = {{1, 2, 3},{4, 5, 6},{7,8,9} };
Like 1-D arrays, you can access individual cells in a 2-D array by using subscripts that specify the indexes of the cell you want to access. However, you now have to specify two indexes instead of one. The expression looks like this:
arr[2][3]=5;System.out.println(arr[2][3]); // prints out 5
2
is the row index3
is the column index5
is the value at this indexYou can also find the length of a row or a column using the following syntax:
arr[2][].length; // prints length of 3rd rowarr[][0].length; // prints length of 1st column
Free Resources