for-each
- Java course
- Beginner
- Lesson 46/116
- 4 min
Learn to iterate arrays and collections with for-each.
for-each
The for-each loop walks through each element of an array or collection in order. No index is needed:
int[] nums = {10, 20, 30};
for (int n : nums) {
System.out.println(n);
}Here n takes one element of the array each turn: 10, 20, 30. for-each is shorter and has no risk of going past the end. It is ideal for read-only use; when you need to modify an element by index, use the classic for.
for-each vs for
The classic for gives an index; for-each gives the element itself. Both walk an array:
String[] names = {"Ayşe", "Alex"};
// Classic for
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
// for-each
for (String name : names) {
System.out.println(name);
}If no index is needed, for-each is cleaner. The array length is read with names.length (no parentheses).
Practice Sum the numbers
Write a Main class with a main method. Assign {5, 10, 15} to int[] nums. Assign 0 to int sum. With for (int n : nums) add each n to sum (sum += n). Finally print System.out.println(sum).
Sample solution
public class Main {
public static void main(String[] args) {
int[] nums = {5, 10, 15};
int sum = 0;
for (int n : nums) {
sum += n;
}
System.out.println(sum);
}
}Expected output
30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the for-each
int[] nums = {1, 2, 3};
for (int n ____ nums) {
System.out.println(n);
}
int[] nums = {1, 2, 3};
for (int n : nums) {
System.out.println(n);
}
Explanation: for-each uses the : separator.
2 Match the for-each concepts
| Term | Meaning |
|---|---|
for |
Loop |
: |
Separator |
nums |
Array |
int n |
Element |
3 When is for-each preferred?
- When an index is needed
- To break the loop
- To read each element Correct answer
- For infinite loops
Explanation: for-each is ideal for reading each element.