Section6.23Enhanced 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”.
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.
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.
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.
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.
I: If you wish to access every element of an array.
II: If you wish to modify elements of the array.
III: If you wish to refer to elements through a variable name instead of an array index.
Only I.
This style of loop does access every element of the array, but using a for-each loop also means the user can access elements through the variable name.
I and III only.
Correct! For-each loops access all elements and enable users to use a variable name to refer to array elements, but do not allow users to modify elements directly.
II and III only.
For-each loops, as well as allowing users to refer to array elements, run through every element. For-each loops also do not allow users to modify elements directly.
All of the Above.
For-each loops access all of an array’s elements and allow users to refer to elements through a variable, but do not allow users to modify elements directly.
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.
The following method has the correct code to return the largest value in an integer array called <i>vals</i> (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.
public int getLargest()
{
---
int largest = vals[0];
---
for (int item : vals)
{
---
if (item > largest)
{
---
largest = item;
---
} // end if
---
} // end for
return largest;
---
} // end method
6-3-8: Given that array is an array of integers and target is an integer value, which of the following best describes the conditions under which the following code segment will return true?
boolean temp = false;
for (int val : array)
{
temp = ( target == val );
}
return temp;
Whenever the first element in array is equal to target.
This would be true if the loop started at the end of the array and moved toward the beginning. But, it will loop from the first element to the last.
Whenever array contains any element which equals target.
This would be true if temp was only set to the result of checking if the current element in the array is equal to target when it is false. But, it is reset each time through the loop.
Whenever the last element in array is equal to target.
The variable temp is assigned to the result of checking if the current element in the array is equal to target. The last time through the loop it will check if the last element is equal to val.
Whenever only 1 element in array is equal to target.
There is no count of the number of times the array element is equal to target.
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.
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.