In Java, there are several ways to print an array. In this guide, we will see various programs to print array using different approaches:
Printing 1D Arrays
1. Using Arrays.toString()
You can use Arrays.toString()
method to print an array. You can simply pass the array reference as an argument to this method to display all the elements of specified array.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(array));
}
}
Output:
[1, 2, 3, 4, 5]
2. Using a Loop
One of the easiest way of displaying all the elements of an array is using a loop. In this program, we are using a for-each loop to print an array.
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
for (int element : array) {
System.out.print(element + " ");
}
System.out.println();
}
}
Output:
1 2 3 4 5
3. Using Iterator
Another way to print an array is by converting it into a list and then using an iterator to display the elements of the list.
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
Iterator<Integer> iterator = Arrays.asList(array).iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
}
}
Output:
1 2 3 4 5
4. Using Stream
You can use the Stream
API to print each element of the array. You can refer Java Stream Tutorial to learn more about Stream.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
Arrays.stream(array).forEach(element -> System.out.print(element + " "));
System.out.println();
}
}
Output:
1 2 3 4 5
5. Using Arrays.asList
Arrays.asList()
is a method in Java that provides an easy way to convert an array into a fixed-size list. This method belongs to java.util.Arrays
class. I have covered some of the commonly used methods here: Java Arrays Methods.
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
Integer[] array = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(array);
System.out.println(list);
}
}
Output:
1 2 3 4 5
Leave a Reply