dev only

Array Traversals

Looping Through an Array

Traversing an array means visiting its elements, usually with a loop. The loop variable doubles as the index:

double[] sensorReadings = {2.1, 2.4, 1.9, 2.2};
for (int i = 0; i < sensorReadings.length; i++)
{
    System.out.println(sensorReadings[i]);
}

Writing the loop against .length (not a hardcoded number) means the same code keeps working no matter how many elements the array actually has.

Arrays Are Objects — Passed by Reference

An array is an object, so passing one into a method passes the reference — changes a method makes to the array's contents are visible back in the caller, same as any mutable object (Ch.7.3):

public static void zeroOut(double[] values)
{
    for (int i = 0; i < values.length; i++)
    {
        values[i] = 0.0; // this really does change the caller's array
    }
}

The Enhanced For-Each Loop

When you just need every value, with no index and no plan to modify elements, the for-each form is simpler:

for (double reading : sensorReadings)
{
    System.out.println(reading);
}

It always starts at index 0 and runs through every element in order. It's genuinely equivalent to an indexed loop — just more concise when you don't need the index.

What For-Each Can't Do

  • Can't modify a primitive array's elements. reading = 0.0; inside the loop only changes the local copy, not the real array — you need an indexed loop (values[i] = 0.0;) to actually change values.
  • Can't get the index. If you need to know where something is, use an indexed loop.
  • Can't skip around or go partway. For-each always visits every element in order, front to back.

Common Pitfalls

  • Off-by-one on the loop bound. i <= values.length runs one iteration too many and throws ArrayIndexOutOfBoundsException; the correct bound is always i < values.length.
  • Expecting a for-each loop to change array values. for (double v : values) { v = 0.0; } compiles, runs, and does absolutely nothing to the real array.
  • Returning "not found" too early in a search. A search loop must check every element before concluding something isn't present — returning false from inside the loop on the first non-match only ever checks the first element.

Key Takeaways

  • Traversing an array means looping through it, index by index, with the loop bound written against .length.
  • Arrays are objects — a method that changes array elements changes the caller's real array too.
  • The for-each loop (for (type v : array)) is simpler when you don't need the index and won't modify elements.
  • For-each cannot modify primitive array elements or provide the index — use an indexed loop for those.

Derived from csawesome-2026: unit-4-data-collections/4.04-array-traversals.md (CSA 4.4)