Accessing 2 Dimensional Arrays
Accessing 2 Dimensional Arrays
So 2D arrays are really just arrays of arrays. So if I have a 2D array with 5 rows and 4
columns, you could think of it as an array containing 5 subarrays that have 4 spots each.
Number of rows: 5
Number of cols: 4
0000
0000
0000
0000
0000
It is important to note that java is considered row major (the row always comes first):
Firstly, Java technically doesn't have 2-dimensional arrays: it has arrays of arrays. So in
Java you can do this:
String arr[][] = new String[] {
new String[3],
new String[4],
new String[5]
};
int rows = arr.length;
There is no requirement that a 2-D array is actually rectangular, or even that all elements in
the first dimension are populated.
If you want to find the number of elements in the first dimension, the answer is
simply array.length.
If you want to find the number of elements in the second dimension of a rectangular
2-D array, the answer is `array[0].length.