In this tutorial, you’ll learn different techniques to print the elements of a given array in Java. Let’s discuss the above methods one by one including examples.
1. Java Arrays.toString() Method
The Arrays.toString() method is the simplest and frequently used method to print an Array in Java programming.
Save above java program in ArrayExample1.java file and compile it and run. You will see the output like below:
2. Using Arrays.deepToString() Method
Java Arrays.deepToString() method is used to fetch the deep content from an array. Here the deep content represents the multidimensional arrays.
Save above java program in ArrayExample2.java file and compile it and run. You will see the below output:
3. Using for Loop
The for loop is a frequently used method used for integrations. We can navigate through all array elements by the array index number. The following example will print array elements using for loop in Java.
Save above java program in ArrayExample3.java file and compile it and run. You will see the below output:
4. Using for-each Loop
For-each is another way for traversing an array than for loop. Here is a quick example of using for-each to get array elements and print them.
Save program in a file named ArrayExample4.java. Then compile the program and run it. You will see the below output:
5. Using Arrays.asList() Method
The asList() is another java function that returns a fixed-size list of a specified array.
Save java program to file named ArrayExample5.java, then compile and run it. You will see the below output:
Wrap Up
In this tutorial, you have learned 5 Java methods to print an array including examples.