Java Array length

by Dimitris Tasios
21 views

In this article, we’ll see how to get the length of an array in Java.

1. How to Get the Length of a 1D Array in Java?

In order to get the length of an array in Java, we use the length property. This property returns an integer indicating the number of elements the array has. Note that this is different from the length() method used in Strings, as we have discussed in our article here. For example, let’s look at the following example:

int[] myNumbers = new int[5];

System.out.println(myNumbers.length); // 5

In this example. the myNumbers array is initialized with a size of 5 elements, so the myNumbers.length will return 5.

2. How to Get the Length of a Multidimensional Array in Java?

In Java, it’s possible to have multidimensional arrays, as described in our article here. A multidimensional array is basically an array whose elements are also arrays. This means that we can get the length of each subarray in the multidimensional array.

Let’s alter our previous example and convert it into a 2D array:

int[][] myNumbers = new int[5][10];

System.out.println(myNumbers.length); // 5
System.out.println(myNumbers[0].length); // 10
System.out.println(myNumbers[3].length); // 10

As you can see, by simply writing myNumbers.length, we get the length of the first dimension only. In order to get the length of a subarray, we have to specify which array we want to get its length from. So, for instance, by writing myNumbers[3].length we get the length of the 4th subarray, which is equal to 10 (remember that arrays are zero-indexed, so we begin counting from 0 instead of 1).

We can extend this kind of logic with as many dimensions as we like. Let’s take a look at a 5D array:

int[][][][][] myNumbers = new int[5][10][13][2][11];

System.out.println(myNumbers.length);              // 5
System.out.println(myNumbers[3].length);           // 10
System.out.println(myNumbers[3][9].length);        // 13
System.out.println(myNumbers[3][9][10].length);    // 2
System.out.println(myNumbers[3][9][10][1].length); // 13

In the example above, we note the length of each dimension, as well as the parent array’s indexes whose subarray we are trying to access. For instance, when we have the statement myNumbers[3][9].length it means that we are trying to access the 10th subarray of the 2nd dimension (which is also the 4th subarray of the 1st dimension), which has a length of 13.

Be careful not to confuse the indexes of an array in a subdimension with the length of one of its subarrays. Having multiple dimensions can prove to be troublesome. Also, note that we cannot write something like myNumbers[3][9][10][1][7].length, since the element at the spot myNumbers[3][9][10][1][7] is an integer and not an array.

4. Conclusion

By now, you should be able to properly use the length property of Java arrays. Be sure to read about how to initialize arrays and what arrays are, in our respective articles here and here.

Related Posts