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

You can use a while loop to print the array. The below given 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.

Output

3) Using enhanced for loop

If you are using Java 1.5 or 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 version, you can use the stream to print 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 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) Using for loop

You can use for loop to print 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

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *