Sub topic 6
Traverse Array Elements with Enhanced for
Visit each value in an array
An array is a group of values stored in order under one name. Each value is an element. When you need to visit every element, Java’s enhanced for loop gives you a short way to do it.
For example, you might use an enhanced for loop to print a list of scores or add them together. The loop takes one element at a time, so you do not need to track its position yourself.
Each pass through the loop is an iteration. During an iteration, a loop variable holds the current element’s value.
A worked example
This program visits three numbers, prints each one, and finds their total.
Save it as ArrayVisit.java:
public class ArrayVisit {
public static void main(String[] args) {
int[] values = {4, 7, 9};
int total = 0;
for (int value : values) {
System.out.println(value);
total = total + value;
}
System.out.println("Total: " + total);
}
}The Java Development Kit, or JDK, provides the tools to compile and run Java programs. With the JDK installed, open a terminal in the folder containing the file and run:
javac ArrayVisit.java
java ArrayVisitThe output is:
4
7
9
Total: 20The loop visits 4, then 7, then 9. On each pass, it prints the current value and adds it to total. After the loop finishes, the program prints the total.
Read the loop header
Look at the first line of the loop:
for (int value : values)
The parts have these roles:
intis the type of each value taken from the integer array.valueis the loop variable. It holds one number at a time.:separates the loop variable from the array to visit.valuesis the array whose elements the loop visits.
The statements between { and } form the loop body. Java runs that body once for each element, in array order.
For the example above, the changes look like this:
| Iteration | Current `value` | `total` after the addition |
|---|---|---|
| 1 | 4 | 4 |
| 2 | 7 | 11 |
| 3 | 9 | 20 |
Once Java has visited the last element, the loop ends. The statement after the loop then prints total.
The loop variable must have a type that can hold an element from the array. For an int[] array, int value works. For a String[] array, you could use a declaration such as String word instead.
Know where the loop variable can be used
A variable’s scope is the part of a program where you can use its name. The loop variable value is available inside the loop body. It cannot be used after the loop ends.
In the example, total is declared before the loop. That lets the program update it inside the loop and print it afterward.
Understand what you can change
For an array of int values, the loop variable receives a copy of each element’s value. Changing that variable does not change the number stored in the array.
Save this example as CopyExample.java:
public class CopyExample {
public static void main(String[] args) {
int[] values = {4, 7, 9};
for (int value : values) {
value = 0;
}
System.out.println(values[0]);
}
}Compile and run it with:
javac CopyExample.java
java CopyExampleIt prints 4, not 0. The assignment changes value during each iteration, but it does not replace the numbers in values.
The expression values[0] reads the first element. The number in brackets is an index: a position in an array. Java array indexes start at zero.
An enhanced for loop is a good choice when you want each element and do not need its index. If you need to know an element’s position or replace values in the array, use an index-based loop instead.
Check empty and missing arrays
An array can have no elements. For example, int[] values = {}; creates an empty integer array. An enhanced for loop over it runs its body zero times.
An empty array is different from null. The value null means a variable does not refer to an array. Trying to visit its elements with an enhanced for loop causes a NullPointerException, which is an error that stops normal execution unless the program handles it.
Practice
Exercise
An array contains {2, 5, 8}. An enhanced for loop starts with total at zero and adds each element to it. What is total after the loop?
Show answer
15. The loop adds 2, then 5, then 8.
Exercise
In for (int score : scores), what does score hold on each iteration? Can it be used after the loop?
Show answer
It holds a copy of the current integer element from scores. Its scope is the loop, so it cannot be used after the loop.