Print Java Array: 3 Methods Explained
In Java, you can use the following method to print all the contents of an array:
- Traverse the array using a for loop, and print each element of the array one by one.
int[] nums = {1, 2, 3, 4, 5};
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
- Convert the array into a stream using Java 8’s Stream API, and print each element using the forEach method.
int[] nums = {1, 2, 3, 4, 5};
Arrays.stream(nums).forEach(System.out::println);
- Use the toString method of the Arrays class to convert the entire array into a string and print it:
int[] nums = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(nums));
The above methods apply to all types of arrays, including both primitive and reference types.