Iterating through arrays is a common task in Java. It is the process of traversing each element one by one.
There are two main ways to iterate through arrays:
-
Using a for loop
-
Using a for-each loop
➢ for Loop Syntax:
Source Code:
public class ForLoopArray {
public static void main(String[] args) {
// Declare and initialize an array of integers
int[] numbers = {10, 20, 30, 40, 50};
// Using a for loop to iterate through the array
System.out.println("Array elements:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}Result:
Ø for-each Loop Syntax:
Source Code:
public class ForEach {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Cherry", "Mango"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
}
}Result:
Watch the video:Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

