Sub topic 6
Traverse array elements with enhanced for
An enhanced for loop visits each value in an array. It is useful when you want to read every value and do not need its position.
An array is a collection of values stored in a fixed order. Each value in the array is called an element. For example, an array might contain the elements 4, 7, and 9.
In this chapter, you will use enhanced for loops to print and add array elements. You will also learn what happens when you change the loop variable and how to handle empty arrays.
Visit every element
Here is a complete Java program:
public class Main {
public static void main(String[] args) {
int[] values = {4, 7, 9};
for (int value : values) {
System.out.println(value);
}
}
}Save it in a file named Main.java. Then compile and run it:
javac Main.java
java MainThe output is:
4
7
9The loop visits the elements in their array order, from first to last. Each pass through the loop is called an iteration. During each iteration, Java gives the next element's value to value. The statements inside the braces are the loop body.
You may also hear this loop called a “for-each” loop. You can read its header as: “For each int value in values.”
Read the loop header
Look at the header from the example:
public class Main {
public static void main(String[] args) {
int[] values = {4, 7, 9};
for (int value : values) {
System.out.println(value);
}
}
}Its parts have different jobs:
| Part | Job |
|---|---|
| `int` | Gives the data type of the loop variable. |
| `value` | Names the loop variable that holds one element's value at a time. |
| `:` | Separates the loop variable from the array. Read it as “in.” |
| `values` | Names the array to visit. |
| `{ ... }` | Holds the statements to run for each element. |
A data type tells Java what kind of value a variable can hold. The array is an int[], so each of its elements is an int. The loop variable is also an int.
The names do not have to be value and values. Choose names that make sense for the data. For an array named scores, you might call each element score.
The loop variable holds only one element's value at a time. In the first iteration, value is 4. In the next, Java gives it 7. In the final iteration, Java gives it 9.
You do not write an element position in the loop header. Java moves through the array for you.
Keep the loop variable in scope
The scope of a variable is the part of a program where you can use its name. A loop variable declared in an enhanced for header is available inside that loop. It is not available after the loop ends.
In the first program, value can be used in the loop body. After the closing brace of the loop, value is no longer in scope. Trying to print it there would cause a compile error: Java would not be able to find that variable.
The array variable values was declared before the loop. It is still in scope after the loop, so you can use values again.
If you need to keep a result after the loop, declare a separate variable before it. The next example does that with a total.
Add the elements
An enhanced for loop can do more than print. This program adds the elements and counts how many are at least 7:
public class Main {
public static void main(String[] args) {
int[] values = {4, 7, 9};
int total = 0;
int count = 0;
for (int value : values) {
total = total + value;
if (value >= 7) {
count = count + 1;
}
}
System.out.println("Total: " + total);
System.out.println("At least 7: " + count);
}
}The output is:
Total: 20
At least 7: 2The total variable is an accumulator: a variable that keeps a running result. It starts at 0, then grows as the loop visits each value.
| Iteration | `value` | `total` after adding | `count` after the test |
|---|---|---|---|
| 1 | 4 | 4 | 0 |
| 2 | 7 | 11 | 1 |
| 3 | 9 | 20 | 2 |
Both total and count are declared before the loop. That lets the program use their final values after the loop ends.
The if statement runs on each iteration. It adds to count only when the current value is at least 7. The loop still visits all three elements.
Handle an empty array
An empty array has no elements. An enhanced for loop over an empty array runs its body zero times.
The next program calculates an average when the array has elements. The average is the total divided by the number of elements.
public class Main {
public static void main(String[] args) {
int[] values = {4, 7, 9};
int total = 0;
for (int value : values) {
total = total + value;
}
if (values.length == 0) {
System.out.println("There are no values to average.");
} else {
double average = (double) total / values.length;
System.out.println("Average: " + average);
}
}
}values.length is the number of elements in the array. The if statement checks it before the program divides. This avoids trying to find an average when there are no values.
The cast (double) changes total to a double for the division. A double can hold a number with a decimal part. Without the cast, dividing two int values would discard the decimal part before the result was stored.
Try changing the array declaration to int[] values = {}; and run the program again. The loop body will not run, and the program will print the message about having no values.
Understand what the loop variable holds
For an array of int values, the loop variable gets a copy of each element's value. Changing the loop variable does not change the element in the array.
Run this program:
public class Main {
public static void main(String[] args) {
int[] values = {4, 7, 9};
for (int value : values) {
value = value + 1;
System.out.println("Loop value: " + value);
}
System.out.println("First array element: " + values[0]);
}
}The output is:
Loop value: 5
Loop value: 8
Loop value: 10
First array element: 4On the first iteration, value gets a copy of 4. The program changes value to 5, but the first array element stays 4. The same thing happens for the other elements.
An index is a numbered position in an array. Java starts array indexes at 0, so values[0] is the first element.
If you need to replace elements in the original array, an index-based loop is usually a better choice. An enhanced for loop gives you each value, but it does not give you its index.
A note about objects
Arrays can also hold references to objects. An object is a value that can hold data. A reference is a way for a variable to access an object.
For an array of references, the loop variable gets a copy of each reference. Changing the loop variable to refer to a different object does not replace the array element. But if you use the reference to change the existing object, that change can be visible through the array.
For example, StringBuilder is a Java type for text that can be changed. Its append action adds text to the end:
public class Main {
public static void main(String[] args) {
StringBuilder[] words = {
new StringBuilder("cat"),
new StringBuilder("dog")
};
for (StringBuilder word : words) {
word.append("!");
word = new StringBuilder("other");
}
System.out.println(words[0]);
System.out.println(words[1]);
}
}The output is:
cat!
dog!On each iteration, word.append("!") changes the object that word refers to. The array still refers to that same object, so the added ! is visible afterward.
The next line makes word refer to a new object. It does not replace the reference stored in the array. This is the same rule as before: assigning to the loop variable does not replace an array element.
Match the element type
The loop variable must have a type that can accept the array's elements. For example, use String for an array of String values:
public class Main {
public static void main(String[] args) {
String[] names = {"Ava", "Bo", "Chen"};
for (String name : names) {
System.out.println("Hello, " + name);
}
}
}A String is a value that holds text. Here, each iteration gives one name to name, then prints a greeting.
If you try to use an unrelated type, Java reports a compile error. For example, an int loop variable cannot hold a String element. Check both the array type and the loop variable type if Java reports a type error in the loop header.
Handle missing values
The word null means there is no object reference. It is important to tell these two cases apart:
- An empty array exists but has no elements. The loop runs zero times.
- An array variable that is
nulldoes not refer to an array. Trying to loop over it causes an error while the program runs.
An array of objects can also exist and contain a null element. In that case, the loop reaches that element and gives null to the loop variable. Check for null before asking that value to do something.
public class Main {
public static void main(String[] args) {
String[] names = {"Ava", null, "Bo"};
for (String name : names) {
if (name == null) {
System.out.println("Missing name");
} else {
System.out.println(name + " has " + name.length() + " letters");
}
}
}
}The output is:
Ava has 3 letters
Missing name
Bo has 2 lettersFor a String, length() gives the number of characters in the text. It cannot be used on null, so the program calls it only in the else part.
Notice the different forms: names.length gives the number of elements in an array, while name.length() gives the number of characters in a string.
Choose the enhanced for loop
Use an enhanced for loop when you want to visit array elements in order and work with each value. It keeps the code short because you do not have to manage an index.
Choose an index-based loop instead when the position matters. For example, you may need an index to print each element's position, replace an element in the array, or compare an element with its neighbor.
| Task | Good choice |
|---|---|
| Print every value | Enhanced `for` |
| Add every number | Enhanced `for` |
| Print each value with its index | Index-based loop |
| Replace each array element | Index-based loop |
Before using an enhanced for loop, check the array itself. It must refer to an array, and its element type must fit the loop variable. If the array can be empty or contain missing values, decide how the program should handle those cases.
Practice
Exercise
For int[] scores = {3, 8, 5};, what does for (int score : scores) { System.out.println(score); } print?
Show answer
It prints 3, then 8, then 5, each on its own line.
Exercise
If an enhanced for loop visits an empty array, how many times does its body run?
Show answer
Zero times. There are no elements to visit.
Exercise
An int[] contains 4 as its first element. Inside an enhanced for loop, you change the loop variable from 4 to 10. What is the first array element afterward?
Show answer
It is still 4. The loop variable held a copy of the element's value.
Exercise
Given an existing int[] values, write a loop that counts the elements greater than 3. Keep the count available after the loop.
Show answer
int count = 0; for (int value : values) { if (value > 3) { count++; } }