Part 03 / Topic 6 of 8
for-each loops
A for-each loop (for (type name : source)) reads every item of something in order, one at a time, without you managing an index. It is the natural way to loop when you don't need the position, only the values.
🔍 About the arrays below:
for-eachneeds something to loop over, and the full array lesson — declaring, sizing, 2D arrays, array methods — is Part 4's job. Here you see only the minimum:int[] marks = {91, 84, ...};makes a fixed list of numbers. Treat it as "just enough syntax to tryfor-eachtoday"; Part 4 explains whatint[]really is.
int[] marks = {91, 84, 76, 68, 95};
int total = 0;
for (int mark : marks) {
total += mark;
}
System.out.println("Total marks: " + total);
System.out.println("Average: " + (total / marks.length));
Output:
Total marks: 414
Average: 82
It works the same way on text:
String[] menuOptions = {"Check balance", "Deposit", "Withdraw", "Exit"};
int number = 1;
for (String option : menuOptions) {
// for-each does not give an index, so we track one ourselves
System.out.println(number + ". " + option);
number++;
}
Output:
1. Check balance
2. Deposit
3. Withdraw
4. Exit
Two limits to know now, so a bug doesn't surprise you later: for-each gives you no index, and the loop variable is a copy — changing it does not change the original array. A counting for loop can do both:
int[] amounts = {100, 200, 300};
for (int amount : amounts) {
amount = amount + 50; // changes only the loop copy, not the array
}
System.out.println("amounts unchanged by for-each: " + amounts[0] + ", " + amounts[1] + ", " + amounts[2]);
for (int i = 0; i < amounts.length; i++) {
amounts[i] = amounts[i] + 50; // a counting for loop CAN update the array
}
System.out.println("amounts updated by counting for: " + amounts[0] + ", " + amounts[1] + ", " + amounts[2]);
Output:
amounts unchanged by for-each: 100, 200, 300
amounts updated by counting for: 150, 250, 350
Rule of thumb: reach for for-each when you only read values in order; reach for a counting for loop when you need the index or you need to write back into the array/list.
Full program: examples/05_for_each_preview.java.
Done here? The practice set for Part 3 — including the solutions — is on the part page.