Java – Iterate over Array Elements
To iterate over the elements of an array in Java, you can use a regular for loop, an enhanced for loop, or a while loop. Each approach visits the array elements one at a time, but the most suitable loop depends on whether you need the element’s index.
Use an index-based for loop when you need the array index, want to update elements by position, or need to traverse in a particular direction. Use an enhanced for loop when you only need to read each element. A while loop is useful when iteration is controlled by a condition in addition to the array index.
Java Array Iteration with a for Loop
An index-based for loop is a common way to traverse a Java array. Array indexes start at 0, and the last valid index is array.length - 1. Therefore, the loop normally starts with index 0 and continues while the index is less than array.length.
for (int index = 0; index < array.length; index++) {
// access array[index]
}
The condition uses <, not <=. If the index becomes equal to array.length, it is outside the valid range of the array.
Example – Iterate over Array Elements – For Loop
In this example, we declare and initialize an integer array nums with six elements. The index variable starts at zero and increases by one after each iteration. The expression nums[index] accesses the element at the current index.
Java Program
/**
* Java Example Program to iterate over Array Elements
*/
public class IterateArray {
public static void main(String[] args) {
int[] nums = {25, 86, 41, 97, 22, 34};
for(int index = 0; index < nums.length; index++) {
//access each element using index
int num = nums[index];
System.out.println(num);
}
}
}
Output
Compile and run the program. Each iteration reads one element from nums and prints it.
25
86
41
97
22
34
The loop executes six times because nums.length is 6. During those iterations, index takes the values 0 through 5.
Iterate over a Java Array with the Enhanced for Loop
The enhanced for loop, also called the for-each loop, directly provides each array element. You do not need to create an index variable or access the array with square brackets.
for (ElementType element : array) {
// use element
}
This form is usually the clearest choice when you need to process every element in order and do not need its index.
Example – Iterate over Array Elements – Enhanced For Loop
In this example, the enhanced for loop assigns each value from nums to the variable num. The loop body then prints that value.
Java Program
/**
* Java Example Program to iterate over Array Elements
*/
public class IterateArray {
public static void main(String[] args) {
int[] nums = {25, 86, 41, 97, 22, 34};
for(int num: nums) {
//access each element
System.out.println(num);
}
}
}
Output
25
86
41
97
22
34
The enhanced for loop visits the elements in array order. It is concise, but it does not directly provide the current array index.
Iterate over a Java Array with a while Loop
A while loop can traverse an array by maintaining an index variable separately. Initialize the index before the loop, test it against array.length, and increment it after processing the current element.
Example – Iterate over Array Elements – While Loop
The following program starts index at 0. While the index is less than nums.length, it reads nums[index], prints the value, and increments the index.
Java Program
/**
* Java Example Program to iterate over Array Elements
*/
public class IterateArray {
public static void main(String[] args) {
int[] nums = {25, 86, 41, 97, 22, 34};
int index=0;
while(index<nums.length) {
//access each element in array
int num = nums[index];
System.out.println(num);
index++;
}
}
}
Output
25
86
41
97
22
34
A while loop produces the same traversal here as the regular for loop. The difference is that initialization and incrementing are written separately rather than in the loop header.
Iterate over a Java Array in Reverse Order
When array elements must be processed from the last element to the first, use an index-based for loop that starts at array.length - 1 and decrements the index.
int[] nums = {25, 86, 41, 97, 22, 34};
for (int index = nums.length - 1; index >= 0; index--) {
System.out.println(nums[index]);
}
Output
34
22
97
41
86
25
The initial index is nums.length - 1 because that is the index of the final element.
Update Java Array Elements While Iterating
If you need to replace values stored in the array, use an index-based loop. The index lets you assign a new value directly to array[index].
int[] nums = {10, 20, 30};
for (int index = 0; index < nums.length; index++) {
nums[index] = nums[index] * 2;
}
for (int num : nums) {
System.out.println(num);
}
Output
20
40
60
Assigning a new value only to the enhanced-loop variable does not replace an element in an array of primitive values. For example, assigning to num in for (int num : nums) changes the local variable, not the corresponding position in nums.
Iterate over a Java Array of Objects
The same loops work with arrays of objects. For example, an enhanced for loop can iterate over each String in a String[].
String[] names = {"Amit", "Neha", "Sara"};
for (String name : names) {
System.out.println(name);
}
Output
Amit
Neha
Sara
The loop variable type must be compatible with the array’s element type. Here, each element of names is a String, so the loop variable is declared as String name.
Iterate over a Two-Dimensional Array in Java
A two-dimensional Java array contains arrays as its elements. To visit every value, use nested loops: one loop for the rows and another for the values in each row.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
for (int[] row : matrix) {
for (int value : row) {
System.out.println(value);
}
}
Output
1
2
3
4
5
6
This approach also works with jagged arrays because the inner enhanced for loop iterates over the actual elements of each row, regardless of that row’s length.
Java for Loop vs Enhanced for Loop for Array Traversal
| Requirement | Suitable loop |
|---|---|
| Read every array element in order | Enhanced for loop |
| Need the current array index | Index-based for loop |
| Replace values at specific indexes | Index-based for loop |
| Traverse the array in reverse | Index-based for loop |
| Iteration depends on additional conditions | while loop or for loop |
For simple read-only traversal, the enhanced for loop usually requires less code. When the position of an element matters, use an index-based loop.
Avoid ArrayIndexOutOfBoundsException During Java Array Iteration
A common iteration error is allowing the index to reach array.length. Since the last valid index is array.length - 1, a forward loop should normally test index < array.length.
for (int index = 0; index < array.length; index++) {
// valid indexes: 0 through array.length - 1
}
Using index <= array.length attempts to access one position beyond the end if the loop body reads array[index].
Java Array Iteration: Key Points
- Use
for (int i = 0; i < array.length; i++)when you need the index. - Use an enhanced
forloop when you only need each element’s value. - Use a
whileloop when keeping the iteration condition separate makes the logic clearer. - The first Java array index is
0, and the last isarray.length - 1. - Use an index-based loop to replace array elements by position.
- Nested loops are used to traverse the rows and elements of multidimensional arrays.
In this Java Tutorial, we learned how to traverse or iterate over Java array elements using regular for, enhanced for, and while loops, and how to handle indexes, reverse traversal, element updates, object arrays, and two-dimensional arrays.
TutorialKart.com