Java Basic Examples

Java Print Array Example

Java print array example shows how to print array in Java. Example also shows how to print array in various ways as well as print 2d array (two dimensional) or multidimensional array.

How to print array in Java?

There are various ways using which you can print array in Java as given below.

1) Java Print Array using while loop

You can use while loop to print array like given below.

Output

2) Java Print Array using for loop

Probably the simplest way to print array in Java is printing it using a for loop as given below.

Output

3) Java Print Array using enhanced for loop

If you are using Java 1.5 or later version, you can use enhanced for loop instead of for loop as given below.

Output

4) Java Print Array using Arrays class

Arrays class provides many useful utility methods and toString method is one of them. It converts array to string which can then be printed as given below.

Output

If you want to remove square brackets and comma from the output, you can remove them using regular expression as given below.

Output

5) Java Print Array using Java 8 Stream

If you are using Java 8 version, you can use stream to print array as given below.

Output

6) Java Print Array using Java 8 String join

If you are using Java 8, you can use join method of String class to join array elements by delimiter as given below.

Output

7) Java Print Array using Apache Commons library

Finally, if you are using Apache Commons library, you can use join method of StringUtils class to join the array elements and print them as given below.

Output

join method is overloaded for byte array, char array, double array, float array, int array, long array and Object array.

How to print 2D array (two dimensional array)?

If you have two dimensional array, you can print it using below given approaches.

a) Print two dimensional or 2D array using for loop

You can use for loop to print two dimensional array as given below.

Output

b) Print two dimensional or 2D array using Arrays class

You can also use deepToString method of Arrays class to print two dimensional array as given below.

Output

Please let us know your views in the comments section below.

 

Join 1000+ fellow learners! Enter your email address below: