How to Iterate Over Array in Java: Simple Syntax and Examples
In Java, you can iterate over an array using a
for loop with an index or an enhanced for-each loop. The for loop lets you access elements by their position, while the for-each loop simplifies reading each element directly.Syntax
There are two common ways to iterate over an array in Java:
- For loop: Use an index to access each element by position.
- Enhanced for loop (for-each): Automatically goes through each element without using an index.
java
int[] numbers = {1, 2, 3, 4, 5}; // For loop syntax for (int i = 0; i < numbers.length; i++) { int element = numbers[i]; // Use element } // Enhanced for loop syntax for (int element : numbers) { // Use element }
Example
This example shows both ways to print all elements of an integer array.
java
public class ArrayIteration { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; System.out.println("Using for loop:"); for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } System.out.println("Using enhanced for loop:"); for (int num : numbers) { System.out.println(num); } } }
Output
Using for loop:
10
20
30
40
50
Using enhanced for loop:
10
20
30
40
50
Common Pitfalls
Common mistakes when iterating arrays include:
- Using
i <= array.lengthinstead ofi < array.length, which causes an error because array indexes start at 0 and go tolength - 1. - Modifying the array size inside the loop (arrays have fixed size).
- Using enhanced for loop when you need the index (then use regular for loop).
java
int[] arr = {1, 2, 3}; // Wrong: causes ArrayIndexOutOfBoundsException for (int i = 0; i <= arr.length; i++) { System.out.println(arr[i]); } // Right: for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }
Quick Reference
Use this quick guide to choose the right loop:
| Loop Type | When to Use | Example |
|---|---|---|
| For loop | Need index or modify elements | for (int i = 0; i < arr.length; i++) |
| Enhanced for loop | Just read elements easily | for (int num : arr) |
Key Takeaways
Use a for loop with index to access elements by position in an array.
Use an enhanced for loop to read each element simply without index.
Always use
i < array.length to avoid errors.Arrays have fixed size; do not try to change length during iteration.
Choose loop type based on whether you need the index or just the element.