Java Traversing Arrays

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 = 0 starts the counter at 0, the first index.
  • i < marks.length runs while i is valid. Length is 5, so i goes 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 85
Mark at index 1 is 90
Mark at index 2 is 78
Mark at index 3 is 92
Mark at index 4 is 88

An 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

85
90
78
92
88

๐Ÿงฎ 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:

  • total starts at 0, since nothing is added yet.
  • Each pass adds the current mark, so total grows: 85, 175, 253, 345, 433.
  • After the loop, total holds the full sum.
  • Dividing by marks.length gives 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: 433
Average: 86.6

We 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:

  • max starts at marks[0], so the first guess is the first value.
  • Each pass, if mark beats max, the new value becomes max.
  • By the end, max holds the biggest value.
  • For the smallest, start min at marks[0] and flip the comparison to <.

Output

Highest mark: 92

Start 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: 2

Now 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: true

The 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 - 1 starts at the last index, 4 for an array of length 5.
  • i >= 0 keeps 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

88
92
78
90
85

โœ๏ธ 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

90
95
83
97
93

Why 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 into mark each pass.
  • mark = mark + 5 changes 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 <= length reads past the end and throws ArrayIndexOutOfBoundsException. Stop at length - 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-code i < 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 - 1 and reaches values with array[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. 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. 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. 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. 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.

Java Multidimensional Arrays

Share & Connect