This write-up is going to cover the various ways of printing an array in java:
- How to Print an Array using for-loop
- How to Print an Array using for-each loop
- How to Print an Array using Java built-in methods
- How to Print a Multidimensional Array
So let’s begin!
How to Print an Array using for loop
Java for loop is one of the simplest and easiest ways of printing the array’s elements. The below-given example will provide more clarity of this concept:
In the below-given snippet, we have an array that consists of five elements. In order to print the elements of the array, we are going to use java for loop:
In the above snippet, the for loop is initialized from 0, will execute until the specified condition stays true i.e. i< array’s length and add 1 to the value of i in every iteration.
From the above snippet, it is clear that the for loop succeeds in printing every single element of the array.
How to Print an Array using for-each loop
For-each loop traverses through the whole array therefore it is among one of the frequently utilized methods to print the array’s elements.
The below-code snippet, we have a string type array of length 5, and we will print each element of the array using the for-each loop:
The complete code and its respective output is shown in the below-given snippet:
The output validates the working of for-each loop.
How to Print an Array using Java built-in methods
Java offers a wide range of built-in methods that can be used to print the elements of an array for example Arrays.toString(), Arrays.asList() etc.
In the below-given code snippet, we are going to use the Arrays.toString() method which will return the string representation of the array’s elements:
We will get the following output on successful execution of the code:
The above snippet verifies the working of the toString() method.
How to Print a Multidimensional Array
In java, we can print the elements of a multidimensional array as well, for better understanding consider the below-given example.
In the below-given code snippet, we will show you how to print the values of a multidimensional array:
To print a multidimensional array we have to utilize the nested loops. The above-code snippet will produce the following output:
This is how we can print a multidimensional array in java.
There are multiple ways to print the elements of an array such as Arrays.toString() method, Java loops, iterator interface, etc. The length attribute is used within a loop to find the array’s length and specify it as termination condition. The “System.out.println()” can be used along with above-mentioned methods to print the array’s elements. This write-up covers different aspects of how to print an array in java.