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.
1 2 3 4 5 6 7 8 9 |
public class ForLoopExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } } } |
- 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.
1 2 3 4 5 6 7 8 9 |
public class ForEachExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; for (int num : numbers) { System.out.println(num); } } } |
- 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.
1 2 3 4 5 6 7 8 9 10 11 |
public class WhileLoopExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; int i = 0; while (i < numbers.length) { System.out.println(numbers[i]); i++; } } } |
- 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.
1 2 3 4 5 6 7 8 9 10 11 |
public class DoWhileLoopExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; int i = 0; do { System.out.println(numbers[i]); i++; } while (i < numbers.length); } } |
- 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.
1 2 3 4 5 6 7 8 9 |
import java.util.Arrays; public class StreamExample { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; Arrays.stream(numbers).forEach(System.out::println); } } |
Arrays.stream(numbers)
creates a stream from the array..forEach(System.out::println)
prints each element.