How to Print an Array in Java

How to Print an Array in Java

Introduction

Printing an array is a quick way to give us visibility on the values of the contents inside. Sometimes the array values are the desired output of the program.

In this article, we'll take a look at how to print an array in Java using four different ways.

While the "best way" depends on what your program needs to do, we begin with the simplest method for printing and then show more verbose ways to do it.

Print an Array Using Arrays.toString() and Arrays.deepToString()

The built-in toString() method is an extremely simple way to print out formatted versions of objects in Java.

Every data type in Java is considered a class and by default, every class inherits from java.lang.Object, the root of Java's class hierarchy. That's why every class has a toString() method. However, arrays don't override the toString() method to format the output nicely, and it just returns the inherited value, which is the hash of the object.

We print arrays using the toString() method from the class in java.util.Arrays.

Take this example where we print the values of an array of integers:

int[] intSequence = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

System.out.println(Arrays.toString(intSequence));

The code above will output the following:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note how all the elements are comma-separated and in square brackets. This method is like a visual representation of the array.

We can use this method to print arrays of different types as well:

double[] doubleValues = {5.5, 2.37, 9.9, 1.02};
System.out.println(Arrays.toString(doubleValues));
        
String[] stringValues = {"alabama", "arkansas", "kentucky"};
System.out.println(Arrays.toString(stringValues));

These respectively result in:

[5.5, 2.37, 9.9, 1.02]
[alabama, arkansas, kentucky]

The toString() method is only effective for one-dimensional arrays. When we have nested arrays we need use the deepToString() method:

double[][] coordinates = {{40.50, 50.75}, {22.25, 32.75}};
System.out.println(Arrays.deepToString(coordinates));
        
String[][] songLines = {{"Take your nose off my keyboard"}, {"What you bothering me for?"}};
System.out.println(Arrays.deepToString(songLines));

These result in:

[[40.5, 50.75], [22.25, 32.75]]
[[Take your nose off my keyboard], [What you bothering me for?]]

If you need a visual of what's in your array at a glance, the toString() and deepToString() methods are your best option.

However, these methods don't allow you to format your output. This approach is basically just a workaround for the fact that arrays don't override the toString() method by default.

If you'd prefer some flexibility with the formatting, you might consider using Java 8 Streams.

Print an Array Using Java 8 Streams

One option for printing an array is to convert it to a stream of objects, then print each element in the stream. We have a few options to leverage streams to print our array.

For example, we can print our array line by line like this:

String[] languages = {"Java", "Python", "JavaScript"};
Arrays.stream(languages).forEach(System.out::println);

In this case, we use the static stream() method of the Arrays class to create a sequential stream of our data. For each element in our stream, we call the println() function on it, making it appear line by line like this:

Java
Python
JavaScript

Note: We reference the println() function like this: System.out::println. The :: in Java is a method reference operator. The forEach() function can either use a lambda function or a method reference.

Alternatively, we can use the Stream class from java.util.stream.Stream to similarly call the println() function on a stream of our array data. We can construct a Stream of this data using Stream.of():

String[] languages = {"Java", "Python", "JavaScript"};
Stream.of(languages).forEach(System.out::println);

With this code we'll get the same output:

Java
Python
JavaScript

Let's try this out with nested arrays as well, adding the release dates of the initial versions of these languages:

String[][] languages = {{"Java", "1996"}, {"Python", "1994"}, {"JavaScript", "1995"}};

Arrays.stream(languages).forEach(System.out::println);
// OR
Stream.of(languages).forEach(System.out::println);

The output for each print via streams would look something like this:

[Ljava.lang.String;@e9e54c2
[Ljava.lang.String;@65ab7765
[Ljava.lang.String;@1b28cdfa

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

That doesn't work very well... We're calling println() on array objects again. We'll have to stream those objects again, and print their elements.

To print nested arrays, we can use a lambda expression in the forEach() function that can go to the second level, by making another stream of each level, and printing the entries out that way:

String[][] languages = {{"Java", "1996"}, {"Python", "1994"}, {"JavaScript", "1995"}};
        
Arrays.stream(languages).forEach(s -> Arrays.stream(s).forEach(System.out::println)); 
// OR
Stream.of(languages).forEach(s -> Arrays.stream(s).forEach(System.out::println));

This lambda function prints the elements in each nested array. When compiled and executed, we would get this output:

Java
1996
Python
1994
JavaScript
1995

Streams make working with collections a breeze. But Java is flexible to provide even more ways. The traditional for-loop does a lot for us still. Let's have a look at printing an array with loops.

Print an Array by Converting to List

You can easily convert a Java array into a List implementation. There are various ways to do that, and we've covered each in detail in our How to Convert a Java Array to ArrayList article.

In short, calling toString(), or just printing out (which implicitly calls toString()) on a List implementation, will print out the contents:

Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> numberList = Arrays.asList(numbers);

System.out.println(numberList);

This results in:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Additionally, you can use .forEach() natively on any Collection, which a List is. So, you can just go ahead and do this as well:

Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Arrays.asList(numbers).forEach(System.out::println);

Though, this isn't a nicely formatted option:

12345678910

You can ditch the method reference and just use a lambda for more control:

Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Arrays.asList(numbers)
        .forEach(number -> System.out.print(String.format("%d, ", number)));

This results in:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 

Print an Array Using For Loops

A more well-known approach to printing an array in Java is to use a for loop. With a for loop we get the index of the element, and we can use the index to get the element of an array.

We set up a for loop with a variable, commonly named i, as the counter starting from element 0. This is then followed by the condition that compares i to the number of elements in the array.

Note: The number of elements in the array that will be used in the loop's condition should never be hardcoded. Java provides an attribute called length that allows the programmer to dynamically calculate the number of elements in an array.

Last but not least, our for loop takes the incremental value in our case we will use the i++ notation to keep increasing our counter by one element in each iteration.

Once our loop is all set and ready, we will simply use the System.out.println() statement to display each element in the array using the rectangular bracket notation [i] taking as input our counter i.

Here's an example where we print all the elements of an integer array line by line:

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (int i = 0; i < numbers.length; i++){
    System.out.println(numbers[i]);
}

Executing this code would print the following in your console:

1
2
3
4
5
6
7
8
9
10

There isn't much more to using for loops. They're quite flexible and conceptually simple. For example, if you had nested arrays then you'll use nested for loops.

Finally, let's have a look at iterators and lists.

Converting To List and Using an Iterator

A Java iterator object allows us to display each element of our array without having to use the index approach we covered in the for loop section.

To use iterators, we have to change the datatype of the array to a List. We can do this by using the Array.asList() method and save the list values returned in a new variable. The asList() method takes in the array, and turns it into a List implementation.

Next, you will need an iterator object to set up your array iterator. An iterator is like a pointer that points to every element in the array. The iterator helps you to inspect each element in a singular manner.

To create an iterator object, we will use the iterator() method of our List. Once our iterator object was created we use the while loop as it offers a more compact way of printing each element return by the iterator.

The while loop's condition will contain a call to the hasNext() method of our iterator. Inside the while loop, we print each element by calling System.out.println(). We get elements from the iterator by calling the next() method. The while loop will keep iterating over each element until we have traversed our array (via the List).

Here's an example where we take an array of integers and print each element line by line by using an iterator:

Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> numberList = Arrays.asList(numbers);
Iterator<Integer> numberIterator = numberList.iterator();

while(numberIterator.hasNext()) {
    System.out.println(numberIterator.next());
}

Compared to the for loops, this method is preferred by developers who rather not deal with array indices. You are guaranteed the upcoming element with next(). Iterators are powerful because we use this same flow for any type of List like an ArrayList or a LinkedList, as well as other collections like a Map or a Set!

Conclusion

In this article, we covered the main methods used to print an array in Java. We started by using the built-in Java methods toString() and deepToString().

From there, we used streams so that we can quickly print array elements line by line. We've also covered how to convert an array to a list, which you can either just call or use the Java 8 Stream API for more granular control.

Then, we used the traditional for loop structure to print every element individually.

Last but not least, we used the iterator object to print every element separately using the next() method inside a while loop. The approaches covered in the chapter can be used depending on the use case and the problem you are trying to solve.

Last Updated: February 9th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Mohamed EchoutAuthor

I am a very curious individual. Learning is my drive in life and technology is the language I speak. I enjoy the beauty of computer science and the art of programming.

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    Better understand your data with visualizations

    With over 330+ pages, you'll learn the ins and outs of visualizing data in Python with popular libraries like Matplotlib, Seaborn, Bokeh, and more.

    © 2013-2021 Stack Abuse. All rights reserved.