Skip to content

Java Print Array Example

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

How to print an array in Java?

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

1) Using while loop

We can use a while loop to print the array. The below-given code example prints an array of String.

Output

2) Using for loop

Probably the simplest way to print an array is to print it using a for loop as given below. The array index starts at 0 and go up to array length – 1 index.

Output

3) Using enhanced for loop

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

Output

4) Using Arrays class

The Arrays class provides many useful utility methods and the 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 a regular expression as given below.

Output

5) Using Java 8 Stream

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

Output

6) Using Java 8 String join

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

Output

7) Using Apache Commons library

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

Output

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

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

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

a) Using for loop

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

Output

b) Using Arrays class

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

Output

This example is a part of the Java Array tutorial with examples.

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

About the author

Leave a Reply

Your email address will not be published.