Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Array Loop: Index, Enhanced, and Stream Approaches

Learn the main ways to loop over arrays in Java: index-based for, enhanced for, and streams, with practical guidance on when each approach fits.

~5 min readJava
#Java#arrays#iteration#for-loop
Diagram comparing three Java array loop approaches: index-based for, enhanced for, and stream iteration.

Iterating over an array is a common task in Java. The main choices are the index-based for loop, the enhanced for loop, and the stream-based approach. The best choice depends on whether you need the index, whether you need to update elements in place, whether you need early exit, and how you want to process the results.

The Classic Index-Based for Loop

The index-based for loop gives you explicit control over the index variable. It is the right choice when you need to know the position of an element, update an element in place, or compare an element with its neighbors.

java
int[] numbers = {10, 20, 30, 40}; for (int i = 0; i < numbers.length; i++) { numbers[i] = numbers[i] * 2; }

The condition i < numbers.length is evaluated on each iteration. For a fixed array this is predictable and efficient. Valid indices run from 0 to length - 1, so a common bug is using <= as the boundary; when i reaches length, numbers[i] throws ArrayIndexOutOfBoundsException.

The index variable also makes it easy to access neighboring elements, such as comparing numbers[i] with numbers[i - 1].

The Enhanced for Loop (for-each)

The enhanced for loop, introduced in Java 5, removes the index variable and iterates directly over each element. It is the most readable option when you only need to read values.

java
int[] numbers = {10, 20, 30, 40}; for (int number : numbers) { System.out.println(number); }

This form works for arrays and for any object that implements Iterable. For arrays, the compiler translates it into an index-based loop, so it is not slower than a hand-written for loop in typical code.

For primitive arrays, the loop variable is a copy of the element, so assigning number = ... does not change the array. For arrays of objects, the loop variable holds the same reference, so you can mutate the object's internal state, but you cannot replace the reference stored in the array.

Using Arrays.stream() and Streams

Java 8 introduced the Stream API, and Arrays.stream() lets you treat an array as a stream of elements. This is useful when you want to chain operations like filtering, mapping, or reducing without writing an explicit loop.

java
int[] numbers = {10, 20, 30, 40}; int sum = Arrays.stream(numbers) .filter(n -> n > 15) .sum();

Arrays.stream() works for primitive arrays and object arrays. For a primitive array it returns a specialized stream such as IntStream or DoubleStream, with methods like sum(), average(), and boxed(). For an object array it returns a Stream<T>.

Streams are more declarative and can be more concise for complex transformations, but they are not a drop-in replacement for every loop. They don't expose the index, and they are designed to process the stream once; a stream cannot be reused. If you need early exit or index-based access, a loop is usually clearer.

Performance Considerations for Array Iteration

For typical application code, the performance difference among these approaches is small. The index-based loop and the enhanced for loop over an array both compile to direct array access, and the JIT can optimize them. Streams add an abstraction layer and can create short-lived objects, so they are usually not the first choice for a very hot loop after profiling has identified a bottleneck.

The source-level condition i < numbers.length is evaluated on each iteration. Because an array's length never changes, the JIT can hoist the length check out of the loop when it can prove the array reference is not reassigned. Reassigning the array variable inside the loop changes the loop's behavior and can prevent that optimization.

Modifying Arrays While Iterating

Arrays have a fixed size, so you cannot insert or remove elements. If you need a filtered or larger collection, create a new array or use a collection such as ArrayList.

To replace elements in place, use the index-based for loop; it is the only one of the three approaches that gives you the array slot to assign to. The enhanced for loop gives you only a copy of the element's value or reference. Streams are designed for functional transformations, so don't modify the source array from inside a stream operation. Side effects on the source can produce inconsistent results and are harder to reason about than an explicit loop.

Choosing the Right Loop for Your Use Case

Use the index-based for loop when you need the index, when you must update elements in place, or when you need to compare neighboring elements. Use the enhanced for loop when you only read values and do not need the index. Use streams when you want to chain operations such as filter, map, and collect without writing loop mechanics.

For example:

  • Summing every value: the enhanced for loop is simple and clear.
  • Doubling every element: the index-based loop is required because you need to write back to the array.
  • Collecting only even numbers into a List: a stream with filter and collect expresses the intent directly.

There is no universal best choice. The right pattern depends on the operation and on the level of abstraction you want in the code.

Common Pitfalls with Array Loops

A frequent mistake is using the enhanced for loop to modify array elements; assignments to the loop variable do not affect the array. In index loops, off-by-one errors are also common, especially when using <= or starting at 1 instead of 0. When iterating backward, use i >= 0 as the condition and i-- as the update.

With arrays of objects, watch for null values. An enhanced for loop throws NullPointerException if you dereference a null element. You can guard inside the loop, or for object arrays use Arrays.stream(array).filter(Objects::nonNull) before further processing.

Finally, remember that streams are single-use. If you need to process the same array multiple times, create a new stream for each pass or use a loop.

Understanding these details helps you write array iteration that is correct, readable, and maintainable. Choose the pattern that fits the operation, not the one that looks most modern.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.