An array becomes truly useful when you can process all of its elements efficiently. Array traversal means visiting each element of an array one by one, usually to read, display, calculate, search, or modify its values.
In Java, loops are the natural tool for array traversal. The two approaches you will use most often are the traditional for loop and the enhanced for-each loop.
Why Is Array Traversal Needed?
Suppose an array contains the marks of 1,000 students. Printing or processing every value individually would require a huge amount of repetitive code. A loop allows the same operation to be applied to every element with just a few lines.
int[] marks = {78, 85, 91, 88, 76}; for (int i = 0; i < marks.length; i++) { System.out.println(marks[i]); }
The loop begins at index 0 and continues until the index reaches marks.length - 1. During each iteration, marks[i] accesses the current element.
Traversing with a for Loop
The traditional for loop is one of the most important techniques for array traversal because it gives you direct access to the index.
int[] numbers = {10, 20, 30, 40, 50}; for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }
The output is:
10 20 30 40 50
The variable i represents the current index. Each time the loop runs, it moves to the next index.
| Iteration | i | numbers[i] |
|---|---|---|
| 1 | 0 | 10 |
| 2 | 1 | 20 |
| 3 | 2 | 30 |
| 4 | 3 | 40 |
| 5 | 4 | 50 |
Why Use length Instead of a Fixed Number?
A common beginner approach is to write the array size directly inside the loop.
for (int i = 0; i < 5; i++) { System.out.println(numbers[i]); }
Although this works for an array containing five elements, it is fragile. If the array size changes later, the loop may no longer work correctly. Using numbers.length automatically adapts the loop to the actual array size.
Best Practice: Use array.length when traversing an array instead of hard-coding its size.
Traversing with the Enhanced for Loop
Java provides an enhanced for loop, commonly called the for-each loop, specifically for convenient traversal of arrays and other collections.
int[] numbers = {10, 20, 30, 40, 50}; for (int number : numbers) { System.out.println(number); }
Here, Java automatically takes each element from numbers and places it into the variable number. You do not need to manage the index manually.
Remember: Use a traditional for loop when you need the index. Use a for-each loop when you simply need each value.
Comparing for and for-each
| Feature | for Loop | for-each Loop |
|---|---|---|
| Index available | Yes | No direct index |
| Syntax | More detailed | More concise |
| Reading elements | Excellent | Excellent |
| Accessing specific positions | Easy | Not directly available |
| Best for | Index-based processing | Simple sequential processing |
Calculating the Sum of Array Elements
Traversal is often used to perform calculations. For example, you can calculate the total of all numbers in an array.
int[] numbers = {10, 20, 30, 40, 50}; int sum = 0; for (int number : numbers) { sum += number; } System.out.println("Sum = " + sum);
The loop visits every element and adds it to sum. The final result is 150.
Finding the Largest Element
Traversal can also be used to compare elements and find the largest value.
int[] numbers = {45, 12, 89, 34, 67}; int largest = numbers[0]; for (int number : numbers) { if (number > largest) { largest = number; } } System.out.println("Largest = " + largest);
The first element is initially treated as the largest. Each following element is compared with it, and the variable is updated whenever a larger value is found.
Modifying Elements During Traversal
A traditional for loop is useful when you need to modify array elements because it gives direct access to their indexes.
int[] numbers = {10, 20, 30, 40}; for (int i = 0; i < numbers.length; i++) { numbers[i] = numbers[i] * 2; }
After traversal, the array contains 20, 40, 60, and 80.
Important: Changing the loop variable in a for-each loop does not replace the corresponding array element for primitive values. Use an index-based loop when you need to update array positions.
Traversing an Array Backward
Sometimes an application needs to process elements from the last position toward the first. A traditional for loop makes this straightforward.
int[] numbers = {10, 20, 30, 40, 50}; for (int i = numbers.length - 1; i >= 0; i--) { System.out.println(numbers[i]); }
The traversal begins at the last valid index and moves backward until index 0 is reached.
Traversing with Conditions
Traversal becomes more powerful when combined with conditional statements. For example, you can print only the even numbers from an array.
int[] numbers = {11, 20, 35, 42, 56, 71}; for (int number : numbers) { if (number % 2 == 0) { System.out.println(number); } }
The loop visits every element, while the condition determines which values should actually be processed.
Common Traversal Mistakes
- Starting the loop at index 1 instead of index 0.
- Using <= array.length instead of < array.length.
- Hard-coding the array size inside the loop.
- Using a for-each loop when the element index is required.
- Accidentally modifying the wrong array position.
A Classic Boundary Error
Consider the following code:
int[] numbers = {10, 20, 30}; for (int i = 0; i <= numbers.length; i++) { System.out.println(numbers[i]); }
This code fails because when i becomes 3, it attempts to access numbers[3]. The last valid index is 2.
Quick Rule: For forward traversal, the safest standard pattern is i = 0; i < array.length; i++.
Practical Example
Imagine an online store storing the quantities of five products currently available in a warehouse. Traversal can be used to calculate the total inventory.
int[] stock = {12, 8, 25, 10, 15}; int totalStock = 0; for (int quantity : stock) { totalStock += quantity; } System.out.println("Total stock = " + totalStock);
The important lesson is not the specific calculation. It is the pattern: obtain an array, traverse its elements, perform an operation, and produce a useful result. This pattern appears constantly in real applications.
Interview Insight
A common interview question is: “How do you traverse an array in Java?” A strong answer should mention both the traditional for loop and the enhanced for-each loop. Explain that the traditional loop is preferred when indexes are needed, while the enhanced loop is cleaner when only the element values are required.
| Task | Recommended Approach | Reason |
|---|---|---|
| Print every element | for-each | Simple and readable |
| Access indexes | for | Provides the current index |
| Modify elements | for | Allows assignment through an index |
| Calculate a total | for or for-each | Both work well |
| Traverse backward | for | Provides index control |
Array traversal is the bridge between storing data and actually doing useful work with it. Once you can confidently move through every element, you can build operations such as searching, filtering, counting, sorting, finding minimum and maximum values, and calculating statistics.
