Java – Print Array Elements
In this tutorial, we will learn how to traverse through an array in Java, and print those elements in the array one by one.
We can use any of the looping statements and iterate through the array. Going forward in this tutorial, we shall go through example programs, that use while loop, for loop, and advanced for loop to iterate through elements and print them.
Print Array Elements using While Loop
To traverse through elements of an array using while loop, initialize an index variable with zero before while loop, and increment it in the while loop. Prepare a while loop with condition that checks if the index is still within the bounds of the array. And for the body of while loop, print the element of array by accessing it using array variable name and index.
Algorithm
Following would be the detailed steps to print elements of array.
- Start.
- Take array in nums.
- Initialize an variable for index and initialize it to zero.
- Check if index is less than length of the array nums. If the condition is false, go to step 7.
- Access the element nums[index] and print it.
- Increment index. Go to step 4.
- Stop.
Main.java
public class Main {
public static void main(String[] args) {
int[] nums = {25, 87, 69, 55};
int index = 0;
while (index < nums.length) {
int num = nums[index];
System.out.println(num);
index++;
}
}
}
Output
25
87
69
55
Print Array Elements using For Loop
We can use for loop to iterate over array elements and print them during each iteration.
The difference between while loop and for loop is that we write statements to initialize and update loop control variables in the for loop in a single line.
The algorithm we used for the above example using while loop, will still hold for this program of printing array elements using for loop.
In the following java program, we shall use for loop to iterate and print the element of given array.
Main.java
public class Main {
public static void main(String[] args) {
int[] nums = {25, 87, 69, 55};
for(int index = 0; index < nums.length; index++) {
int num = nums[index];
System.out.println(num);
}
}
}
Output
25
87
69
55
Print Array Elements using Advanced For Loop
Advanced For Loop in Java is an enhancement for the regular loop, in case of iterating over an iterable.
In the following program, we shall iterate over the array nums
. During each iteration, we get the element to variable num
.
Main.java
public class Main {
public static void main(String[] args) {
int[] nums = {25, 87, 69, 55};
for(int num: nums) {
System.out.println(num);
}
}
}
Output
25
87
69
55
Conclusion
In this Java Tutorial, we have written Java programs to print array elements, using different looping statements available in Java.