← Back to Chapters

Java Array Traversal

? Java Array Traversal

? Quick Overview

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.

? Key Concepts

  • Arrays store elements in contiguous memory locations
  • Index starts from 0 and ends at length - 1
  • Traversal is usually done using loops
  • Java supports both indexed and enhanced traversal

? Syntax / Theory

  • for loop – full control using index
  • while loop – condition-based traversal
  • enhanced for – simple read-only traversal

? Code Example(s)

? View Code Example
// 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]);
}
}
}
? View Code Example
// 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);
}
}
}

? Interactive Simulator

Visualize how the loop visits every index. Click "Next Step" to iterate.

int[] arr = {10, 20, 30, 40, 50};
10
20
30
40
50
> Console initialized...

? Live Output / Explanation

Output

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.

✅ Tips & Best Practices

  • Always use array.length to avoid index errors
  • Prefer enhanced for loop when index is not required
  • Use standard loops when you need element positions

? Try It Yourself

  • Traverse an array of strings and print each value
  • Find the sum of all array elements
  • Print only even numbers from an integer array