Module 7: Arrays and ArrayList
Looping Through Arrays
Use `for` and enhanced `for` loops to process every value in an array without repetitive code.
Author
Java Learner Editorial Team
Reviewer
Technical review by Java Learner
Last reviewed
2026-04-16
Java version
Java 25 LTS
Learning goals
- Loop through arrays with a regular `for` loop
- Use the enhanced `for-each` loop for simple reads
- Choose the loop style that matches the task
Arrays are often used together with loops: Once you have several values, looping becomes the natural way to process them all.
A regular for loop is useful when you need the index: It helps when you want positions, replacement, or side-by-side calculations.
The enhanced for-each loop is useful when you only need each value: It reads cleanly for simple printing or summing tasks.
Pick the simpler loop when possible: Use indexes only when the problem really needs them.
Runnable examples
Regular `for` loop with indexes
public class Main {
public static void main(String[] args) {
String[] names = {"Ada", "Grace", "Linus"};
for (int i = 0; i < names.length; i++) {
System.out.println(i + ": " + names[i]);
}
}
}Expected output
0: Ada 1: Grace 2: Linus
Enhanced `for-each` loop
public class Main {
public static void main(String[] args) {
int[] numbers = {2, 4, 6};
for (int number : numbers) {
System.out.println(number);
}
}
}Expected output
2 4 6
Mini exercise
Print every score in an array using a `for-each` loop.
Summary
- Use `for` when you need indexes.
- Use `for-each` when you only need values.
- Loops turn grouped data into practical work.
Next step
Now apply loops to common array tasks such as totals, maximum values, and searching.
Sources used