Array traversal in Java means accessing each element of an array one by one. It is commonly used to read, display, update, or process array values efficiently.
0 and ends at length - 1
// Traversing an array using a for loop
class ArrayTraversal {
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]);
}
}
}
// Traversing an array using enhanced for loop
class EnhancedTraversal {
public static void main(String[] args) {
int[] numbers = {5, 15, 25, 35};
for(int num : numbers) {
System.out.println(num);
}
}
}
Visualize how the loop visits every index. Click "Next Step" to iterate.
int[] arr = {10, 20, 30, 40, 50};
Each element of the array is printed on a new line in the order it is stored. The enhanced loop automatically accesses elements without using indexes.
array.length to avoid index errors