Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 201 ยท Arrays

Looping Through Arrays

Loop through Java arrays with for and for-each - sum, max, min and average, searching, counting, reversing in place, modifying elements and copying arrays safely.

An array on its own just stores values. The useful work happens when a loop walks through it: adding up a column of numbers, finding the highest score, checking whether a name is on a list, flipping the order. These few patterns appear in almost every program you'll write, in Java and in every other language.

This lesson shows each pattern with the loop that fits it best: the for-each loop when you only need the values, and the classic for loop when you need positions or want to change elements. It ends with the right ways to copy an array, which matters because, as you saw in Arrays, assigning one array variable to another doesn't copy anything.

for or for-each?

Both loops from for Loops work with arrays:

Java
int[] scores = { 72, 95, 88 };

for (int i = 0; i < scores.length; i++) {   // classic: you get the index
    IO.println(i + ": " + scores[i]);
}

for (int score : scores) {                  // for-each: you get each value
    IO.println(score);
}

Choose with one question: do you need the index?

You want to... Use
read every value, in order for-each
know the position of an element (print "#3", return where something is) classic for
change elements (a[i] = ...) classic for
go backward, skip elements, or step by 2 classic for
walk two arrays side by side classic for

For-each is shorter and can't be off by one, so it's the default. Its loop variable is a copy of each element: assigning to it doesn't change the array.

Sum, average, max and min

The accumulator pattern keeps a running result in a variable declared before the loop and updates it on every element:

Java Statistics for one array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three details make this correct:

  • Start max and min from a real element, here dailySteps[0]. Starting highest at 0 breaks for arrays of negative numbers. If you prefer a neutral start, use Integer.MIN_VALUE for a maximum and Integer.MAX_VALUE for a minimum.
  • Use a wide enough accumulator. Adding many int values can overflow; a long total is cheap insurance. (See Working with Numbers for overflow.)
  • Cast before dividing. total / dailySteps.length with two integers would throw away the decimal part. Casting one side to double gives a real average.

All of these, except the overflow-safe sum, crash or misbehave on an empty array: dailySteps[0] throws, and dividing by a length of 0 gives NaN for a double. Check array.length == 0 first whenever an array could be empty.

Where is the maximum?

To report which element is largest, track its index instead of its value. That needs the classic loop:

Java
int bestDay = 0;
for (int i = 1; i < dailySteps.length; i++) {
    if (dailySteps[i] > dailySteps[bestDay]) {
        bestDay = i;
    }
}
IO.println("Most steps on day " + (bestDay + 1));

Starting at i = 1 is fine because index 0 is already the current best. Using > (not >=) keeps the first maximum when there's a tie.

Counting and filtering

Counting is the accumulator pattern with an if. Here the loop counts passing grades and also builds a smaller array of just those grades:

Java Count, then collect matches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because arrays can't grow, the program counts first and then creates an array of the exact size. The expression passing[next++] = grade stores at index next and then moves next forward, a compact idiom you'll see often. In real code you'd often reach for an ArrayList or a stream (Arrays.stream(grades).filter(g -> g >= 60).toArray()), but the two-pass loop shows what those tools do for you.

Searching

A linear search checks each element in turn until it finds a match. Return or record the index as soon as you find it, and use a value like -1 to mean "not found", because -1 can never be a valid index:

Java Find the position of a value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Compare strings with equals, never == (see Strings). The break stops the search at the first match, which also saves time on long arrays. When you only need a yes/no answer, a boolean found flag works the same way.

A linear search looks at up to every element, so its cost grows with the array's length. If the array is sorted, Arrays.binarySearch finds an element in a handful of steps even among millions; it's covered in The Arrays Class.

Modifying elements

To change elements you need the index, so use the classic loop and assign to array[i]:

Java
double[] prices = { 19.99, 5.49, 120.00 };
for (int i = 0; i < prices.length; i++) {
    prices[i] = prices[i] * 0.9;          // 10% off every price
}

A for-each version (for (double p : prices) { p = p * 0.9; }) compiles but changes only the local copy p, which is one of the most common silent bugs in beginner Java.

There's one subtlety with arrays of objects. The for-each variable is a copy of the reference, so you can't replace the element, but you can call methods that change the object it points to:

Java
StringBuilder[] lines = { new StringBuilder("a"), new StringBuilder("b") };
for (StringBuilder line : lines) {
    line.append("!");                     // changes the object: works
    line = new StringBuilder("zzz");      // replaces the local copy: no effect
}
// lines now holds "a!" and "b!"

Reversing an array

There are two ways to reverse: build a new array in the opposite order, or swap elements in place. In-place reversal walks two indexes toward each other and swaps the pair at each step, which needs no extra array:

Java Reverse in place with two indexes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The swap uses a temporary variable because letters[left] = letters[right] would otherwise overwrite the value you still need. The condition left < right stops in the middle. A loop that ran all the way to the end would swap every pair twice and leave the array exactly as it started.

The index formula length - 1 - i maps position 0 to the last index, 1 to the second-to-last, and so on. It's worth memorizing; it shows up whenever you read an array backward.

Walking two arrays together

When two arrays line up by position (parallel arrays), one index drives both:

Java
String[] items = { "Tea", "Bread", "Eggs" };
int[] quantities = { 2, 1, 12 };

for (int i = 0; i < items.length; i++) {
    IO.println(quantities[i] + " x " + items[i]);
}

This works, but parallel arrays are fragile: nothing guarantees both arrays have the same length or stay in step when one is sorted. Once you've met Records, an array of record Item(String name, int quantity) keeps related values together and is usually the better design.

Copying arrays

Since int[] b = a; copies only the reference, you need a real copy whenever you want to change one array without affecting the other. Java offers several ways:

Way What it does
a manual loop full control, e.g. copying with a transformation
a.clone() a new array with the same length and elements
Arrays.copyOf(a, newLength) a copy that can be shorter (truncated) or longer (padded with defaults)
Arrays.copyOfRange(a, from, to) a copy of the part from index from up to, not including, to
System.arraycopy(src, srcPos, dest, destPos, count) copies into an existing array; the fastest way to move a block
Java clone, copyOf and System.arraycopy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

System.arraycopy doesn't create an array; the destination must already exist and be large enough, or it throws ArrayIndexOutOfBoundsException. It correctly handles overlapping regions in the same array, as the shift at the end shows (the last element stays, because nothing was copied over it).

All of these copies are shallow. For an array of objects, the new array holds the same references, so both arrays point to the same objects. Changing an object through one array is visible through the other. A deep copy, where every object is duplicated too, needs a loop that copies each element (see Copying Objects). For arrays of primitives and of immutable objects like String, shallow copies are all you ever need.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does prices contain after double[] prices = {1.0, 2.0}; for (double p : prices) { p = p * 10; }?

    The for-each variable p is a copy of each element, so assigning to it never changes the array. Use a classic for loop with prices[i] = ... to modify elements.
  2. 2. Why is int max = 0; a bad starting value when finding the largest element?

    For an array like {-5, -2, -9}, no element beats 0, so max stays 0. Start from the first element or from Integer.MIN_VALUE.
  3. 3. In a reversal loop over an array of length n, which index pairs with index i?

    Index 0 must pair with the last index, n - 1. The formula n - 1 - i gives n - 1 for i = 0, n - 2 for i = 1, and so on.
  4. 4. What does Arrays.copyOf(new int[] {4, 5, 6}, 5) return?

    copyOf creates an array of the requested length. A longer copy is padded with the default value, which is 0 for int.
  5. 5. After StringBuilder[] b = a.clone();, where a is an array of StringBuilder objects, what is true?

    clone() makes a shallow copy. The array is new, so assigning b[0] = ... doesn't affect a, but both arrays share the element objects.

Summary

  • Use for-each to read every value; use the classic for when you need the index, want to change elements, go backward or walk two arrays at once.
  • Accumulators (sum, count, max, min) live in variables declared before the loop; start max/min from a real element and watch for empty arrays.
  • Linear search returns the index of the first match, or -1 when there is none; compare strings with equals.
  • Assigning to a for-each variable never changes the array.
  • Reverse in place by swapping a[left] and a[right] while left < right; length - 1 - i is the mirror index.
  • Copy with clone(), Arrays.copyOf, Arrays.copyOfRange or System.arraycopy; all of them make shallow copies.

Next: Multidimensional Arrays, where arrays hold other arrays to model grids, tables and matrices.