Java One Dimensional (1D) Arrays: Accessing Elements
Accessing an Array Element
Now that we have created an array and populated its elements with values how do we access them? When we created the array we used a pair of open/close square brackets to to denote a 1D array. The square brackets are used whenever we refer to elements of an array, either creating an array of elements or accessing an element. When accessing a element we need to inform Java which element specifically want to access, and we do that using the index number. The general syntax is:
arrayName[x];
Here, x represents the index number. Let’s look at a practical example using the studentGrades array. Let’s work out how to display the value of the last element in the array. There are a number of way to to do this, the most obvious might be to work out what the index of the last element is. Let’s remind ourselves of the array structure:
Index: | 0 | 1 | 2 | 3 | 4 |
Data: | 82 | 76 | 65 | 92 | 55 |
This array has 5 elements and we can see that the last element, with a value of 55, is in index position 4. So, using the correct syntax we can write code that will access and display the value of element index 4:
int [] studentGrades = {82, 76, 65, 92, 55}; System.out.println(studentGrades[4]);
And not surprisingly the output displays the value of that element:
run: 55 BUILD SUCCESSFUL (total time: 0 seconds)
What if we didn’t know which index position the last element was in?
Is there anything we have learnt so far that might help us find an index position?
Could the length of the array help?
Take some time to consider this problem, and write a program that will return the value of the last element without explicitly referring to it. When you are finished you can check your solution below, but try before clicking!
OK, so we know that the length property will return the number of elements in a 1D array, AND we know that the index of the last element of an array is the length of that array -1. Putting all that together, we can find the value of the last element by using the length-1 as the index position, right? Let’s see if that works:
// The array: int [] studentGrades = {82, 76, 65, 92, 55}; // Find the length of the array int arrayLength = studentGrades.length; // Subtract 1 from the length to get the last index position int lastPosition = arrayLength-1; // Use the lastPosition to output the value System.out.println(studentGrades[lastPosition]);
And the output is:
run: 55 BUILD SUCCESSFUL (total time: 0 seconds)
That’s pretty cool, we got the right result! But I can’t help thinking that’s a lot of code, is there any way we can improve it?
The above solution works but could be better. IF you have something similar, have another look at your code and try to make improvements and reduce the amount of code you are using. When you are finished you can check your solution below, but try before clicking!
So, the first solution made a lot of use of variables to store the length and index position. Often it is wise to make use of variables especially if you will need those values later in your program but in this case we don’t need to. Let’s work out some of the numbers to see if we can simplify our calculation:
First, the length of the array will give us the number of elements:
studentGrades.length
Next, we know that the last element is the length of the array -1, so this is the same as:
studentGrades.length-1
Now, if the above returns the index value of the last element, why not simply use that?
studentGrades[studentGrades.length-1]
Let’s try it and see:
// The array: int [] studentGrades = {82, 76, 65, 92, 55}; // Output the last element of the array: System.out.println(studentGrades[studentGrades.length-1]);
And the output is:
run: 55 BUILD SUCCESSFUL (total time: 0 seconds)
The result is exactly the same, but the code is much reduced and a lot more efficient.
This is something you should always strive to do – review your code periodically with a view to improving efficiency and legibility.
Accessing an entire Array
Accessing elements in arrays is a common requirement if any Java program. So far we have accessed one element, but what about accessing an entire array?
An array is a series of elements, and to access one element requires an index position – by extension to access all elements would require all index positions. It sounds like we would need to step through the array, element by element, until we have accessed all elements. Is there anything we have learnt so far that might help us achieve this?
Does this sound like a loop? Is accessing an element, then another, then another the same as accessing an element then changing the index position before repeating the same action over and over?
Let’s remind ourselves of how loops work, and specifically for loops:
for (initialise; test; increment) {
statements;
}
Once the loop variable has been initialised with a value, that value is then tested against a condition which, if evaluated to true, the loops code block will be executed. Once all statements within the code block have been executed the loop variable is incremented and the test process is repeated.
The for loop we need to write will start with the first array element and then execute a code block that will display the value of the current element. This will be repeated for as many times as there are elements – no more and no less. The output should be a list of every value stored within the array.
We can call the loop variable anything we want, but it’s best to keep them short and simple like a single letter. Let’s call ours i. These variables are typically integers that are initialised with a value of 0. This value could work well for us since the first element in every array has an index of 0, so let’s start with that:
for (int i = 0; test; increment) {
statements;
}
Next we need to think about what we are testing. The variable is i and we need this loop to continue as many times are there are elements in the array. We know how to find the number of elements in any 1D array by using the length property, so how about we use that to allow the loop to continue as long as i remains within the limit of the array elements:
for (int i = 0; i < studentGrades.length; increment) {
statements;
}
Next we need to increment i for when the code has successfully executed ready for the next iteration of the test stage:
for (int i = 0; i < studentGrades.length; i++) {
statements;
}
OK, we have a for loop that will execute a code block for as many times as there are elements in the array, but what needs to be in the code block to output the value of the array elements? We know how to access a single element in a 1D array using arrayName[x] where x represents the index number.
Should we create a new variable for this purpose? That would work if the variable started with a value of 0 to match the first array element and then increment each time the loop is executed, something like:
int x = 0;
for (int i = 0; i < studentGrades.length; i++) {
studentGrades[x];
x++;
}
But wait, don’t we already have a variable that starts with a value of 0 and is incremented each time the loop executes? Just because the loop variable i has a specific job to do doesn’t mean we can’t reuse it elsewhere in our code, and we are exercising our mantra of reviewing our code to improve efficiency and legibility. OK, our program now looks like this:
for (int i = 0; i < studentGrades.length; i++) {
studentGrades[i];
}
If we ran this we wouldn’t see much, yes we are accessing the array element values but we have nothing in there that would output that value. By using the System.out.println() method and inserting the element value code, studentGrades[i], we can fix that:
int [] studentGrades = {82, 76, 65, 92, 55}; // for loop for (int i = 0; i < studentGrades.length; i++) { System.out.println(studentGrades[i]); }
The output lists all of the array elements, no more and no less thanks to our use of the array length property to determine exactly how many elements are in the array:
run: 82 76 65 92 55 BUILD SUCCESSFUL (total time: 0 seconds)