Enhanced For-Loop (For-Each) for Arrays
Introduction: 6.3.0
for each loopis an enhanced kind of for loop- It is easier to write
- doesn’t involve an index variable
- sets a variable to each value in the array successively
- It is easier to write
- type of variable must be the type used in the array
- Can also work with other collections like
ArrayLists
int[] testScores = {33, 94, 87, 76};
for (int score : scores) {
System.out.println(score);
}
For-each loop limitations: 6.3.1
- You can’t modify array values using a for-each loop
- You can’t use an index
- You can’t iterate parts of an array, or do a different order
Summary: 6.3.4
- A for-each loop can be used to loop through an array without using an index
- Includes a variable; enhanced for loop variable
- holds a copy of each value of the array
- enhanced for loops can be rewritten to use regular for or while loops

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.