Java programming course: 6.3 Looping over arrays

In the previous lesson we defined a class that utilises an array.


Looping over arrays

Java allows four different mechanisms for looping over the elements of an array. Looping is sometimes referred to as iteration.

The standard "for" loop

The standard for loop is in the following format:

for (initialiser; condition; increment) {
    // code to work on each element goes here…
}
 

Note the following:

  • The initialiser defines a variable (usually of type int) to serve as the index within the loop. It is common to use the identifier i, although more meaningful variable names may be more appropriate in some cases
  • The condition is an expression that that involves the identifier specified in the initialiser, and returns a boolean to control whether the loop should continue
  • The increment simply changes the value of the initialiser identifier (often just by adding one) for the next iteration of the loop

Example: To iterate over the animals in the pen, first retrieve the array of animals:

Animal[] animalsInPen = penguinPen.getAnimals(); 

Now you can iterate over them with the following code:

for (int i = 0; i < penguinPen.getCount(); i++) {
    System.out.println(animalsInPen[i]);
}
 

Note the following:

  • It is most common when iterating over an array to set the initialiser variable (i in this case) to zero, although you may in fact start from any element you wish. The variable i is local to the for block, so it ceases to exist as soon as all of the iterations complete
  • The condition checks whether the current value of the initialiser variable is less than the number of animals in the pen, which it can find out using the getCount() method on the pen
  • It is most common to increment the initialiser variable by one, but you may increment by any value you wish, or decrement instead if you are iterating in reverse order

The above loop is only iterating the specific number of times corresponding to the actual number of animals in the pen (making use of the getCount() method), rather than iterating over all ten elements of the array. When you need to iterate over every array element then all arrays have a publicly available length attribute (not method) which will provide that number. Change the above for statement as indicated:

for (int i = 0; i < animalsInPen.length; i++) { 

The above will iterate over all ten array elements, but be aware that you only added two animals to the pen so after the first two elements the remaining eight elements will all be null. To ignore these, you would need an extra conditional check, as follows:

for (int i = 0; i < animalsInPen.length; i++) {
    if (animalsInPen[i] != null) {
        System.out.println(animalsInPen[i]);
    }
}
 

A better approach would be for the getAnimals() method to only return the array items that aren't null, so modify it as follows:

public Animal[] getAnimals() {
    return Arrays.copyOfRange(animals, 0, nextElementIndex);
}
 

The Arrays class is in package java.util which you will therefore need to import.

The copyOfRange() static method of Arrays returns a new array based on a subset of a given array, using the first and last index range specified in arguments two and three. The check for null is no longer required in the loop:

for (int i = 0; i < animalsInPen.length; i++) {
    System.out.println(animalsInPen[i]);
}
 

The "for-each" loop

The "for-each" loop is a simplified version of the standard for loop and follows this format:

for (Type variableName : array) {
    // do something with variableName …
}
 

Note the following:

  • Type must be the same primitive or reference type the array was defined to contain
  • variableName will contain the current primitive value or object reference
  • array is the name of the array you want to loop over

You could use the "for-each" looping mechanism to iterate over the animalsInZoo array as in the following method:

for (Animal anAnimal : animalsInPen) {
    System.out.println(anAnimal);
}
 

In the above, the variable anAnimal will contain each array element's Animal object reference in turn.

Although the syntax of the "for-each" mechanism is simpler than the standard for loop, the main disadvantage is that you do not now have the element index number during each iteration.

The "while" loop

The while looping mechanism repeats a block of code while a boolean condition is true, and follows this format: 

while (condition) {
    // do something…
    // modify condition to avoid infinite loop
}
 

Applied to the animalsInPen array you could iterate as follows:  

int index = 0;
while (index < penguinPen.getCount()) {
    System.out.println(animalsInPen[index]);
    index++;
}
 

Note the following:

  • A local int variable called index is defined before the while loop
  • The condition is that the value of index must be less than the number of animals in the pen
  • The value of index is incremented inside the while loop block. Failure to do this would result in an infinite loop
  • It is possible that the code inside the while block may not be executed at all if the boolean condition is false to start with

The "do-while" loop

The "do-while" loop is similar to the "while" loop except that the conditional check is performed at the end of the block. It follows this format:

do {
    // do something
    // modify condition to avoid infinite loop
} while (condition);
 

Applied to the animalsInPen array you could do this:

int index = 0;
do {
    System.out.println(animalsInPen[index]);
    index++;
} while (index < penguinPen.getCount());
 

The primary difference compared to the normal "while" loop is that "do-while" will always execute the code inside the block at least once, since the conditional check only occurs at the end of the block. You therefore need to reinstate the check for null, since if no animals at all are in the pen you need to prevent the access to the first element.


In the next lesson we will show how arrays can be sorted into a sequence.

Next lesson: 6.4 Sorting arrays 


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Saturday, 13 December 2025

Captcha Image