In Java, looping through an array or Iterating over arrays means accessing the elements of the array one by one. We have multiple ways to loop through an array in Java.
Example 1: Here, we are using the most simple method i.e. using for loop to loop through an array.
// Java program to loop through
// an array using for loop
import java.io.*;
class GFG {
public static void main(String args[]){
// taking an array
int a[] = { 1, 2, 3, 4, 5 };
int i, x;
// Iterating over an array
for (i = 0; i < a.length; i++) {
// accessing each element of array
x = a[i];
System.out.print(x + " ");
}
}
}
Output
1 2 3 4 5
Example 2: The another method is using enhanced for loop to iterate over arrays in Java. It is same as for loop where rather than using index we directly iterate on elements.
// Java Program to iterate over arrays
// using enhanced for loop
import java.io.*;
public class GFG {
public static void main(String[] args)
{
// Array Created
int a[] = { 1, 2, 3, 4, 5 };
// Iterating using for-each or
// enhanced for loop
for (int i : a)
System.out.print(i + " ");
}
}
Output
1 2 3 4 5
Example 3: We can also loop through an array using while loop. Although there is not much of a difference in for and while loop in this condition. While loop is considered effective when the increment of the value depends upon some of the condition.
// Java program to iterate over an array
// using while loop
import java.io.*;
class Main {
public static void main(String args[])
{
// taking an array
int a[] = { 1, 2, 3, 4, 5 };
int i = 0;
// Iterating over an array
// using while loop
while (i < a.length) {
// accessing each element of array
System.out.print(a[i] + " ");
i++;
}
}
}
Output
1 2 3 4 5
Example 4: We can also use the Arrays.stream() method. This Method is used to convert an Array into stream and then we can traverse stream using forEach() loop.
// Java Program to iterate over arrays
// using Arrays.stream() Method
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// Array Created
int[] a = { 1, 2, 3, 4, 5 };
// Iteration using Arrays.stream()
Arrays.stream(a).forEach(i -> System.out.print(i + " "));
}
}
Output
1 2 3 4 5