Java Traversing Arrays
Table of Contents + โ
In the last lesson you learned about Java accessing array elements. The real power shows up when you pair an array with a loop. That is traversing: visiting every element in turn, like a teacher walking down a row of desks.
๐ค Why traverse with a loop?
Adding 100 marks by hand is impossible. A loop and an array both speak in numbers, so they fit together:
- An array stores values at numbered positions, starting from 0.
- A loop produces those same numbers, one after another.
- The loop hands you each index, and you use it to reach the value.
Every task below is the same shape: walk the array, do something small at each stop.
๐ Way 1: the index for loop
A for loop counts from 0 up to length - 1. The counter is the index, so you reach each value with array[i]. Learn this one first because it shows exactly what happens at each step.
This loop prints every mark next to its position.
int[] marks = {85, 90, 78, 92, 88};
for (int i = 0; i < marks.length; i++) { System.out.println("Mark at index " + i + " is " + marks[i]);}Read the loop one piece at a time:
int i = 0starts the counter at 0, the first index.i < marks.lengthruns whileiis valid. Length is 5, soigoes 0, 1, 2, 3, 4.i++moves to the next index each pass.marks[i]reads the value at the current index.
When i reaches 5 the condition is false and the loop stops. The index is right there in your hands, so use this loop when the position matters.
Output
Mark at index 0 is 85Mark at index 1 is 90Mark at index 2 is 78Mark at index 3 is 92Mark at index 4 is 88An array of length 5 has indexes 0, 1, 2, 3, 4. Five slots, but the last number is one less than the length. The last index is always length - 1.
Use < length, not <= length
The condition must be i < marks.length, not i <= marks.length. The last valid index is length - 1. Using <= would try to read marks[5] on the final pass. That slot does not exist, so Java throws an ArrayIndexOutOfBoundsException and your program crashes.
๐ Way 2: the for-each loop
If you only need the values, the enhanced for loop is cleaner. It is called the for-each loop, read as โfor each value in the arrayโ. It hands you each value directly, with no counter to manage.
Here is the same printing job written with for-each.
int[] marks = {85, 90, 78, 92, 88};
for (int mark : marks) { System.out.println(mark);}Read it as โfor each mark in marksโ. No i, no marks.length, no marks[i]. Java visits the array and gives you one value at a time, in order. mark is just a label for the current value.
Why have two loops? Each is good at a different thing:
- for-each is shorter and safer when you only look at values. No index to get wrong.
- index loop gives you the position number, which for-each hides. Some tasks need that position.
Output
8590789288๐งฎ Summing and averaging an array
Letโs add up all the marks and find the average. The pattern is an accumulator: keep a running total and add to it on each pass.
Here is the full program.
public class Average { public static void main(String[] args) { int[] marks = {85, 90, 78, 92, 88}; int total = 0;
for (int mark : marks) { total = total + mark; }
double average = (double) total / marks.length; System.out.println("Total: " + total); System.out.println("Average: " + average); }}What each part does:
totalstarts at 0, since nothing is added yet.- Each pass adds the current
mark, sototalgrows: 85, 175, 253, 345, 433. - After the loop,
totalholds the full sum. - Dividing by
marks.lengthgives the average. - The
(double)cast forces real division. Without it, Java chops off the decimals.
The code is the same whether the array has 5 marks or 500. That is the payoff of traversing.
Output
Total: 433Average: 86.6We used for-each here because we only needed the values, not their positions.
๐ Finding the largest and smallest value
To find the biggest mark, keep track of the largest value seen so far and update it whenever a bigger one shows up.
Here is the code for the largest value.
public class Largest { public static void main(String[] args) { int[] marks = {85, 90, 78, 92, 88}; int max = marks[0]; // start by assuming the first is biggest
for (int mark : marks) { if (mark > max) { max = mark; // found a bigger one, remember it } }
System.out.println("Highest mark: " + max); }}The logic is a running champion:
maxstarts atmarks[0], so the first guess is the first value.- Each pass, if
markbeatsmax, the new value becomesmax. - By the end,
maxholds the biggest value. - For the smallest, start
minatmarks[0]and flip the comparison to<.
Output
Highest mark: 92Start max at the first element, not at 0. If every number were negative, 0 would be bigger than them all and max would never update. The first real element is always safe.
๐ Counting matches and searching for a value
Two more everyday tasks: counting how many values pass a test, and checking whether a value is present.
First, counting. To find how many marks are 90 or above, keep a counter and add 1 each time a value qualifies.
int[] marks = {85, 90, 78, 92, 88};int passCount = 0;
for (int mark : marks) { if (mark >= 90) { passCount++; // โ
this one qualifies, count it }}
System.out.println("Marks 90 or above: " + passCount);The counter starts at 0 and grows only when the test passes. Here 90 and 92 qualify, so the count ends at 2.
Output
Marks 90 or above: 2Now searching. To check if 78 is in the list, traverse and set a flag the moment you find it.
int[] marks = {85, 90, 78, 92, 88};int target = 78;boolean found = false;
for (int mark : marks) { if (mark == target) { found = true; break; // โ
stop early, no need to keep looking }}
System.out.println("Found " + target + ": " + found);The break matters here. Once the value is found, there is no reason to keep walking. Stopping early saves work on a long list.
Output
Found 78: trueThe break keyword exits the loop right away. Use it whenever a single match is all you need.
๐ Printing in reverse
To walk the array backwards, you need the index loop, since for-each always goes front to back. Start at the last index and count down to 0.
int[] marks = {85, 90, 78, 92, 88};
for (int i = marks.length - 1; i >= 0; i--) { System.out.println(marks[i]);}Read the three parts of the loop:
i = marks.length - 1starts at the last index, 4 for an array of length 5.i >= 0keeps going down to and including index 0.i--steps backward by one each time.
You visit 4, 3, 2, 1, 0, so the values come out reversed. This works only because the index loop lets you pick where to start and which way to step.
Output
8892789085โ๏ธ Modifying each element in place
Sometimes you want to change the values, not just read them. To add 5 bonus points to every mark, you must write back into the array, and only the index loop can do that.
Here we give every mark a 5-point bonus.
int[] marks = {85, 90, 78, 92, 88};
for (int i = 0; i < marks.length; i++) { marks[i] = marks[i] + 5; // โ
writes the new value into the slot}
for (int mark : marks) { System.out.println(mark);}marks[i] = marks[i] + 5 reads the current value, adds 5, and stores it back at index i. The index points at the real slot, so the change sticks. The second loop prints the updated array to prove it.
Output
9095839793Why canโt the for-each loop do this? Look closely.
int[] marks = {85, 90, 78, 92, 88};
for (int mark : marks) { mark = mark + 5; // โ changes the copy, not the array}// marks is still {85, 90, 78, 92, 88}The for-each variable mark is a copy of the value, not the slot:
- For
int, Java copies the number intomarkeach pass. mark = mark + 5changes only that copy, so the real slot never updates.marks[i]points at the actual slot, which is why writing back needs the index loop.
The rule: read with either loop, write back with the index loop.
๐ Which loop should you use?
Both loops traverse an array. Pick fast:
- for-each when you only need values: printing, summing, averaging, counting, searching. Shorter, and no off-by-one trap.
- index loop when you need the position, want to change elements, or want to go backwards.
To remember: for-each is for looking, the index loop is for touching.
โ ๏ธ Common Mistakes
Traversal slip-ups that bite almost everyone:
- Going one step too far.
i <= lengthreads past the end and throwsArrayIndexOutOfBoundsException. Stop atlength - 1.
โ This reads one slot too far and crashes.
for (int i = 0; i <= marks.length; i++) { // โ <= goes too far System.out.println(marks[i]);}โ This stops at the last valid index.
for (int i = 0; i < marks.length; i++) { // โ
< stops correctly System.out.println(marks[i]);}- Starting at index 1. The first index is 0. Starting at 1 silently skips the first value, and nothing crashes, so it is easy to miss.
โ This skips marks[0].
for (int i = 1; i < marks.length; i++) { // โ misses the first value System.out.println(marks[i]);}โ This starts at the beginning.
for (int i = 0; i < marks.length; i++) { // โ
starts at index 0 System.out.println(marks[i]);}- Trying to edit the array in a for-each. The for-each variable is a copy, so assigning to it does not change the array. Use the index loop to modify elements.
โ The array stays unchanged.
for (int mark : marks) { mark = 0; // โ only changes the copy}โ The array really updates.
for (int i = 0; i < marks.length; i++) { marks[i] = 0; // โ
writes into the real slot}โ Best Practices
Habits for clean array traversal:
- Prefer for-each for read-only work. Printing, summing, counting, searching by value, all without index mistakes.
- Use the index loop for positions or edits. Writing back, going backwards, or reporting where a value sits.
- Always loop to
array.length. Never hard-codei < 5. Let the array report its own length, so the code survives a resize. - Initialize accumulators correctly. A sum or count starts at 0. A max or min starts at the first element, never 0, so negatives behave.
- Break early when one match is enough. Stop the moment you find what you want.
๐งฉ What Youโve Learned
Nicely done. Letโs recap.
- โ Traversing means visiting every element of an array, usually with a loop.
- โ
The index for loop uses a counter from 0 to
length - 1and reaches values witharray[i]. It gives you the position. - โ The for-each loop hands you each value directly, with no index, great for read-only work.
- โ Traversal makes classic tasks easy: sum, average, max and min, counting matches, and searching for a value.
- โ Use the index loop when you need the position, want to go backwards, or want to change elements.
- โ A for-each variable is a copy, so it cannot write back into a primitive array. The index loop can.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What condition correctly stops an index loop over an array?
Why: The last valid index is length - 1, so the loop runs while i < array.length.
- 2
When is a for-each loop the better choice?
Why: for-each is ideal for read-only work; it gives values but not positions or the ability to edit.
- 3
When finding the largest value, what should max start as?
Why: Starting max at the first element avoids bugs with negative numbers, where 0 might be wrong.
- 4
Why can't you change array elements with a for-each loop?
Why: The for-each variable holds a copy, so assigning to it does not touch the array; use an index loop instead.
๐ Whatโs Next?
So far every array has been a single row of values. But some data is naturally a grid, like a seating chart or a game board with rows and columns. For that, Java has multidimensional arrays. Letโs learn them next.