Java One Dimensional (1D) Arrays: Length
Length of a 1D array
The length of a 1D array is the number of elements contained within the array. This is an important property of any array as it will help you write code that will fit perfectly within the size of your array and avoid issues like index out of bounds exceptions that can force an early and unexpected termination of your program.
To get the length of any 1D array you will need to know the name of the array and append the property length to it using dot syntax. The general syntax is:
arrayName.length;
This statement will return the number of elements in the array arrayName, but you will need to do something with that number (like assign it to a variable or output it to a console) otherwise it will be lost. Let’s see a practical application of this using the studentGrades array:
int [] studentGrades = {82, 76, 65, 92, 55}; int arrayLength = studentGrades.length; System.out.println(arrayLength);
Here, the returned length of the array studentGrades is assigned to an integer variable named arrayLength. With the number safely stored in a variable we can use it later, but for now the code outputs the length to the console:
run: 5 BUILD SUCCESSFUL (total time: 0 seconds)
We can see the length of the array studentGrades is 5, meaning that there are 5 elements in the array. Each array element has a unique index number associated with it so that we can interact with any element. Index numbers always start from 0, here’s a reminder of the array structure:
Index: | 0 | 1 | 2 | 3 | 4 |
Data: | 82 | 76 | 65 | 92 | 55 |
It is important to see the relationship between an array length and the index numbers. It is easy to mis-count the length of an array if you are looking at the index numbers, they start at 0 and will end at the length of the array-1. Can you see that? The length of the studentGrades array is 5, but he last element in the array has an index of 4. Spend a little time making sure you get that, it will be very useful later.