Looping through an Array

Arrays are one of the fundamental data structures in Java, and looping through them efficiently is a key skill for any Java developer. In this tutorial, we’ll explore different ways to iterate through an array.

for Loop

A traditional for loop is a straightforward way to loop through an array using an index.

  • The loop starts at i = 0 (the first index).
  • It runs until i < numbers.length.
  • The value at numbers[i] is printed in each iteration.

Enhanced for Loop (for-each)

The enhanced for loop, also called a for-each loop, simplifies iteration when we don’t need an index.

  • The loop directly assigns each array element to num in each iteration.
  • No need to use an index explicitly.

while Loop

A while loop is useful when the number of iterations is not fixed beforehand.

  • The loop condition i < numbers.length ensures we don’t go out of bounds.
  • We manually increment i in each iteration.

do-while Loop

A do-while loop guarantees at least one iteration, making it useful in certain scenarios.

  • The loop executes at least once, even if numbers.length is 0.

Streams (Java 8+)

Java Streams provide a functional approach to iterating through an array.

  • Arrays.stream(numbers) creates a stream from the array.
  • .forEach(System.out::println) prints each element.