Verified for the 2025 AP Computer Science A exam•Last Updated on June 18, 2024
When working with arrays, we often need to process all the elements, one by one. This process of visiting each element in an array is called "traversing" the array. In this guide, we'll learn different ways to safely and efficiently go through all the elements in an array.
Traversing an array means visiting each element in the array, usually to perform some operation like:
There are two main approaches to traverse arrays in Java:
This is the most common way to traverse an array when you need to know the position (index) of each element:
int[] numbers = {10, 20, 30, 40, 50};
// Traverse using a standard for loop with index
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at position " + i + ": " + numbers[i]);
}
Key points:
i
represents the current position (index)i
is less than the array's lengthnumbers[i]
When you only need the values and don't care about the positions:
int[] numbers = {10, 20, 30, 40, 50};
// Traverse using enhanced for loop (for-each)
for (int value : numbers) {
System.out.println("Value: " + value);
}
Key points:
Simpler syntax - no need to manage indices
The loop variable (value
) directly holds each element
You don't know which position you're at (no index)
You can't modify the array structure during traversal
Sometimes you might want to use a while loop for traversal:
int[] numbers = {10, 20, 30, 40, 50};
int i = 0;
// Traverse using a while loop
while (i < numbers.length) {
System.out.println(numbers[i]);
i++;
}
Approach | Use When You Need To |
---|---|
Indexed For Loop | Access or change elements based on their position Keep track of position numbers Only process certain elements (like only even indices) |
Enhanced For Loop | Simply process every element without needing position information Write cleaner, more readable code Avoid "off-by-one" errors |
While Loop | Exit early based on a condition Use more complex stepping logic |
When you try to access a position that doesn't exist in the array, Java throws an ArrayIndexOutOfBoundsException. This commonly happens when:
Your loop condition goes too far:
// Error: i will eventually become 5, which is invalid
for (int i = 0; i <= numbers.length; i++) { ... }
You start at the wrong index:
// Error: starting at position 1 skips the first element
for (int i = 1; i <= numbers.length; i++) { ... }
You use the wrong comparison operator:
// Error: using <= instead of <
for (int i = 0; i <= numbers.length; i++) { ... }
Since array indices start at 0 and end at length-1, it's easy to make "off-by-one" errors:
int[] scores = {85, 92, 78, 95, 88};
// INCORRECT: This will cause ArrayIndexOutOfBoundsException
for (int i = 0; i <= scores.length; i++) {
System.out.println(scores[i]); // Error when i = 5
}
// CORRECT version
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
Remember:
<
(less than), not <=
(less than or equal to)length - 1
int[] values = {10, 20, 30, 40, 50, 60, 70};
// Traverse just the first 3 elements
for (int i = 0; i < 3; i++) {
System.out.println(values[i]);
}
// Traverse just the last 3 elements
for (int i = values.length - 3; i < values.length; i++) {
System.out.println(values[i]);
}
int[] numbers = {4, 7, 2, 9, 6, 8};
int searchFor = 9;
boolean found = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == searchFor) {
System.out.println("Found at position: " + i);
found = true;
break; // Exit the loop once found
}
}
if (!found) {
System.out.println("Value not found in the array");
}
int[] scores = {85, 92, 78, 95, 88};
int sum = 0;
for (int score : scores) {
sum += score; // Add each score to the sum
}
double average = (double) sum / scores.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
int[] values = {12, 5, 22, 9, 18, 3, 14};
int min = values[0]; // Start with the first element
int max = values[0];
for (int i = 1; i < values.length; i++) {
if (values[i] < min) {
min = values[i];
}
if (values[i] > max) {
max = values[i];
}
}
System.out.println("Minimum value: " + min);
System.out.println("Maximum value: " + max);
Traversing arrays is a fundamental skill in programming. We've learned how to visit each element in an array using indexed for loops, enhanced for loops, and while loops. We've also covered common traversal patterns and how to avoid the dreaded ArrayIndexOutOfBoundsException by understanding how array indices work. Remember that array indices start at 0 and end at length-1, so always be careful with your loop conditions to prevent "off-by-one" errors.