Java Array – While Loop
Java Array is a collection of elements stored in a sequence. You can iterate over the elements of an array in Java using any of the looping statements.
To access elements of an array using while loop, use index and traverse the loop from start to end or end to start by incrementing or decrementing the index respectively.
In this tutorial, we will learn how to use Java While Loop to iterate over the elements of Java Array.
Example 1 – Iterate Java Array using While Loop
In the following program, we initialize an array of integers, and traverse the array from start to end using while loop. We start with an index of zero, condition that index is less than the length of array, and increment index inside while loop.
During each iteration, we have access to index and the array itself, using which we can access the element.
Java Program
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
int index = 0;
while (index < numbers.length) {
System.out.println(numbers[index]);
index++;
}
}
}
Output
2
4
6
8
10
Example 2 – Iterate Java Array in Reverse using While Loop
You can also traverse through an array from end to start. All you have to do is initialize the index that points to last element of the array, decrement it during each iteration, and have a condition that index is greater than or equal to zero.
In the following program, we initialize an array, and traverse the elements of array from end to start using while loop.
Java Program
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
int index = numbers.length -1;
while (index >= 0) {
System.out.println(numbers[index]);
index--;
}
}
}
Output
10
8
6
4
2
Example 3 – Access Element of Java Array in Steps using While Loop
By incrementing index inside the while loop not by one but more than one, you can hop over the loop, accessing only some elements and interleaving some.
In the following program, we will access first element, leave the second, then access the third, and leave the fourth and so on.
Java Program
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
int index = 0;
while (index < numbers.length) {
System.out.println(numbers[index]);
index += 2;
}
}
}
Output
2
6
10
Conclusion
In this Java Tutorial, we learned how to iterate or traverse through a Java Array using While Loop.