Unit 3 Lesson 7 - Enhanced For Loops (for-each Loops)
Lesson summary and assignments
The enhanced for-loop, known in some programming languages as the for-each loop, is a specialized control structure which visits each member of a collection such as an array or an ArrayList. The type used in the enhanced for-loop must be of the same type as the entries stored in the collection. A couple examples will make this clearer.
int[] scores = {89, 76, 92, 87, 67};
for(int studentScore : scores)
{
System.out.println(studentScore);
}
The previous example has an array of integers. An enhanced for-loop is used to retrieve and print each of the entries in the 'scores' array. The first item within the parentheses of the enhanced for-loop is the type of the entries within the collection which will be traversed. Since the 'scores' array holds integers, the first item in the for-loop parentheses is 'int'. This variable type is followed by the variable name by which the entries of the collection will be accessed, in this case the entries will each be held in a variable called 'studentScore'. Next is a colon, and then comes the variable which holds the collection, in this case 'scores'. Finally is a statement or a curly-brace enclosed code-block which will be executed for-each entry in the collection. In this case, since the enhanced for-loop header specified that each entry of the 'scores' array will be accessed through a variable called 'studentScore', the code block has a line of code which prints the variable 'studentScore'. This results println's for-each of the values 89, 76, 92, 87 and 67.
As a second example, an array of strings is created. An enhanced for-loop is used to print each element of that string array on a single line, each separated by a space. What do you think will be printed by the following code segment?
String[] words = {
"Hello",
"to",
"two",
"of",
"the",
"most",
"awesome",
"people",
"I",
"know!"
};
for(String word : words)
{
System.out.print(word + ' ');
}
System.out.println();
In this case, System.out will print for-each word in the words array. The code segment will print:
Hello to two of the most awesome people I know!
Answers
Vocabulary
This lesson has no new vocabulary.