Introduction
Java’s enhanced for loop, introduced in Java 5, works just as well with collections of objects as it does with collections of primitive values. The only difference is how the data is handled in memory. This concept is rooted in the way Java handles memory management for classes and objects in general.
Please note: to understand this topic you must have a firm grasp on enhanced for loop basics. Also, although not strictly necessary for this droplet, a good understanding of Java memory management is helpful in developing a deep understanding of enhanced for loos with objects.
Syntax
General syntax:
for (class-type referenceVariable : collection) {}
Basic usage:
Given an existing array named arr, filled with objects of a class named ExampleClass, the enhanced for loop would be set up as follows:
for (ExampleClass obj : arr) {}
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.