What’s up Nerd

Java 101: The Difference Between array[0].length and array.length

Light
2 min readDec 12, 2023

--

In Java, a 2D array is an array of arrays, meaning that each element of the 2D array is another 1D array. For example, if you have a 2D array called array, then array[0] is the first 1D array, array[1] is the second 1D array, and so on.

The length property of an array returns the number of elements in that array. Therefore, array.length returns the number of 1D arrays in the 2D array, which is also the number of rows in the 2D array. On the other hand, array[0].length returns the number of elements in the first 1D array, which is also the number of columns in the first row of the 2D array.

For example, suppose you have a 2D array like this:

int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

Then array.length is 3, as there are 3 1D arrays in the 2D array. And array[0].length is 3, as there are 3 elements in the first 1D array. Similarly, array[1].length and array[2].length are also 3, as there are 3 elements in each 1D array.

However, if you have a 2D array like this:

int[][] array= {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};

Then array.length is still 3, as there are 3 1D arrays in the 2D array. But array[0].length is 3, array[1].length is 2, and array[2].length is 4, as there are different number of elements in each 1D array. This is called a jagged array, as the rows have different lengths.

To summarize, the difference between array[0].length and array.length is that the former returns the number of columns in the first row of the 2D array, while the latter returns the number of rows in the 2D array.

--

--