Time estimate: 45 min.

7.3. Enhanced For-Loop (For-Each) for Arrays

There is a special kind of loop that can be used with arrays that is called an enhanced for loop or a for each loop. This loop is much easier to write because it does not involve an index variable or the use of the []. It just sets up a variable that is set to each value in the array successively.

To set up a for-each loop, use for (type variable : arrayname) where the type is the type for elements in the array, and read it as “for each variable value in arrayname”. You may have used a similar loop in AP CSP Pseudocode or App Inventor with lists like below.

../_images/appinvForEachComparison.png

Figure 1: Comparing App Inventor, AP CSP, and Java for each

See the examples below in Java that loop through an int and a String array. Notice the type of the loop variable is the type of the array.

int[] highScores = { 10, 9, 8, 8};
String[] names = {"Jamal", "Emily", "Destiny", "Mateo"};
// for each loop: for each value in highScores
// for (type variable : arrayname)
for (int value : highScores)
{
    // Notice no index or [ ], just the variable value!
    System.out.println( value );
}
// for each loop with a String array to print each name
// the type for variable name is String!
for (String name : names)
{
    System.out.println(name);
}

Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. You can use it whenever you need to loop through all the elements of an array and don’t need to know their index and don’t need to change their values. It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array. This type of loop can only be used with arrays and some other collections of items like ArrayLists which we will see in the next unit.

coding exercise Coding Exercise

Try the following code. Notice the for each loop with an int array and a String array. Add another high score and another name to the arrays and run again.

coding exercise Coding Exercise

Rewrite the following for loop which prints out the even numbers in the array as an enhanced for-each loop. Make sure it works!

7.3.1. Foreach Loop Limitations

What if we had a loop that incremented all the elements in the array. Would that work with an enhanced for-each loop? Unfortunately not! Because only the variable in the loop changes, not the real array values. We would need an indexed loop to modify array elements. Try it in the Active Code below or in the Java visualizer by clicking the CodeLens button and step through the code to see why it doesn’t work.

coding exercise Coding Exercise

The for-each loop below cannot change the values in the array because only the loop variable value will change. Run it with the CodeLens button to see why this is. Then, change the loop to an indexed for loop to make it change the array values.

Note

Enhanced for each loops cannot be used in all situations. Only use for-each loops when you want to loop through all the values in an array without changing their values.

  • Do not use for each loops if you need the index.

  • Do not use for each loops if you need to change the values in the array.

  • Do not use for each loops if you want to loop through only part of an array or in a different order.

exercise Check Your Understanding

7.3.2. Foreach Loop Algorithms

Here is an object-oriented example that has the array as a private instance variable in the class and provides a public method average that uses a for-each loop. You can use the Java visualizer or the Code Lens button to step through this code.

Try the code below.

exercise Check Your Understanding

The following method has the correct code to return the largest value in an integer array called vals (an instance variable of the current object), but the code is mixed up. Drag the blocks from the left into the correct order on the right and indent them correctly as well. You will be told if any of the blocks are in the wrong order or not indented correctly.

If you want to step through the correct code to see what it does in the Java Visualizer click on the following Java visualizer link.

exercise Check Your Understanding

7.3.3. groupwork Programming Challenge : SpellChecker 2

Spell Checker

In the last lesson, you created a spellcheck method using a for loop. In this lesson, you will use enhanced for each loops instead.

  1. Write a new version of the spellcheck method to use an enhanced for-each loop instead of an indexed for-loop. It should take a word as a parameter and return true if it is in the dictionary array. It should return false if it is not found.

  2. Write a method checkText that takes a String array of words which represents sentence of text and then calls your spellcheck method to check if each word in that text is spelled correctly. It should count and print out the misspelled words, and return the number of misspelled words. Some helper code is provided in the main method that will split a String of words into a String array, and remove punctuation and convert to lowercase, before calling this method.

Write a spellcheck() method using an enhanced for-each loop that takes a word as a parameter and returns true if it is in the dictionary array. Return false if it is not found. Write a checkText() method that takes a String[] parameter which is a sentence of text and then calls your spellcheck method above to check if each word in that text is spelled correctly using an enhanced for-each loop. It should return a count of the misspelled words.

7.3.4. groupwork Design an Array of Objects for your Community

In Unit 5, you came up with a class of your own choice relevant to your community. In lessons 6.1 and 6.2, you created an array to hold objects of your class and traversed the array with a loop. In this challenge, we will create a new class that holds your array of objects and add a method that print the array elements and a method that finds a certain object in the array using enhanced for loops. We encourage you to continue working in pairs.

Here is an example of a Student class and a StudentArray class that searches for a student with a specific name. In Java, when you are working with multiple classes on your own computer, each class is usually in its own file that matches the class name. On Runestone, when you are working with multiple classes, only the class that has the main method should be public, and the other classes should start with class instead of public class.

Run the StudentArray class below. Note that it uses the class Student below it and creates an array of Students. Using the StudentArray print() method as a guide, write a StudentArray method called findAndPrint() which takes a String name as an argument, and uses an enhanced for-loop to traverse the array to find a Student in the array with the same name. If the argument equals the Student object’s name (using its getName() method), then print out that student’s info. Call it from the main method to test it.

For your community challenge,

  1. Copy your array of objects code from last lesson 6.2.

  2. Using the StringArray class above as your guide, separate it into your class and a public array class that puts the array of objects in a private instance variable. The main method should be in this class.

  3. Write a print() method that uses an enhanced for-loop to print out the array elements.

  4. Write a findAndPrint() method with an argument that looks for a certain attribute of the objects in the array using an enhanced for-loop, and prints out all the data for the object it finds.

Copy your class from the last last lesson 6.2 below after the ClassNameArray class. Delete the public from in front of that class. On Runestone, only the class that has the main method should be public. Complete the ClassNameArray class substituting in your Class name and using the StudentArray class above as a guide. You should add a print() method and a findAndPrint() method that uses enhanced for loops.

7.3.5. Summary

  • An enhanced for loop, also called a for each loop, can be used to loop through an array without using an index variable.

  • An enhanced for loop header includes a variable, referred to as the enhanced for loop variable, that holds each value in the array.

  • For each iteration of the enhanced for loop, the enhanced for loop variable is assigned a copy of an element without using its index.

  • Assigning a new value to the enhanced for loop variable does not change the value stored in the array.

  • Program code written using an enhanced for loop to traverse and access elements in an array can be rewritten using an indexed for loop or a while loop.

You have attempted of activities on this page