Introduction

Java’s enhanced for loop, otherwise known as the for-each loop, was introduced in Java 5. It is designed to be a shortcut version of the standard for loop, used when you need to loop over an entire array or other collection.

Please note: to understand this topic you must have a firm grasp on for loops with arrays.

How it Works

Syntax

General syntax:

for (datatype localVariable : collection) {}

Standard Java spacing:

Note the spacing, indicated with red hashes (#). It is standard Java convention to place one blank space on either side of the colon:

for#(datatype#localVariable#:#collection)#{}

Basic usage:

Given an existing array of ints named arr, the enhanced for loop would be set up as follows:

for (int a : arr) {}

Examples

Practice

Your turn! Open your Java IDE of choice. (We recommend JetBrains IntelliJ IDEA.)

Project 1:

Create an array of Strings named heroes that contains a collection of names of the main characters in the movie Big Hero 6: Baymax, Hiro, Fred, Go Go, Wasabi, and Honey Lemon. Then use an enhanced for loop to have the entire collection printed out to the console, one name per line.

Expected outcome:

Baymax
Hiro
Fred
Go Go
Wasabi
Honey Lemon

Project 2:

Create an array of doubles named temperatures and fill it with 100 random numbers ranging from 0.0 to 99.9. Using a single enhanced for loop, find the maximum temperature, the minimum temperature, and the average of all the temperatures. Finally, output those values to the console.

Expected outcome (numeric values may differ):

maximum temperature = 99.8
minimum temperature = 1.4
average temperature = 56.3

Assessment:

Sign in to submit your projects for evaluation, take the online completion quiz, notify an instructor of your accomplishment, or apply your work to a stream certificate.