How to Print an Array in Java
An array is an ordered sequence of a certain number of items of the same data type. It is a Java data structure.
Java developers often use arrays to store data. For instance, an array could store the names of five suppliers of cereal bars at a local supermarket. Another array could store the names of nine breeds of fish found in a local lake.
When you’re working with arrays in Java, you may encounter a scenario where you want to print out the contents of an array. There are multiple ways to do this.
This tutorial will discuss, using examples, three approaches you can take to print an array in Java. By the end of this tutorial, you’ll be an expert at printing arrays in Java.
Java Array
Arrays are a crucial component of coding in Java. They allow you to store and access a large number of values efficiently. Instead of declaring a number of different variables to hold values of the same data type, you can declare one array that holds all of the values you want to store.
Here’s an example of an array in Java:
String[] birds; birds = new String[10];
In our code above, we first declared an array, called birds,which is capable of storing string values. Then we assigned the number of string values the birds array can store (10).
Now that we’ve explored the basics of Java arrays, we can discuss how to print an array in Java.
Print an Array Using the Arrays Library
The Java Arrays library provides a number of functions used to work with arrays in Java. One of these functions is the toString()
method, which is used to print the contents of an array to the console.
If we want to use Java’s Arrays library in our code, we first have to import that library. We can do so using the following code:
import java.util.Arrays;
Once we import Java’s Arrays library, we can use its functions.
Let’s suppose we have an array that stores the names of our favorite sandwich shops in town. We are looking for a spot to grab lunch, so we decide to print this array to the console. We can do so using this code:
import java.util.Arrays; class PrintSandwichShops { public static void main(String[] args) { String[] shops = {"Kat's Sandwiches", "Swanson Cafe", "Lakeland's Salads and Sandwiches", "Le Petit Sandwich"}; System.out.println(Arrays.toString(shops)); } }
Our code returns:
[Kat's Sandwiches, Swanson Cafe, Lakeland's Salads and Sandwiches, Le Petit Sandwich]
Let’s break down our code. First we declare an array, called shops, which stores our four favorite sandwich shops as strings. Then we use the Arrays.toString()
method to convert our array into a readable string, and we use println()
to print the items in the array to the console.
Print an Array Using a for-each Loop
In programming, for
loops are used to execute a specific block of code until a certain condition is met. For instance, a for loop may run 10 times until a condition is met, after which point the program will continue past the loop and run the rest of the code.
Developers use for-each loops, also known as enhanced for
loops, to iterate through every item in an array. Combined with a print statement, we can use a for-each loop to iterate through and print to the console every item in an array.
Suppose we have an array that stores the common names of all the birds we saw while birdwatching this year. We want to print the contents of this array to the console so we can review the names of the birds we spotted. We could do so using this code:
class PrintBirds { public static void main(String[] args) { String[] birds = {"Robin", "Chaffinch", "Starling", "Goldfinch", "Great Tit"}; for (String bird: birds) { System.out.println(bird); } } }
Our code returns:
Robin Chaffinch Starling Goldfinch Great Tit
In our code, we used a for-each loop to iterate through the common name of every bird in the birds array and print each bird name to the console.
First, we declared an array called birds, which holds five string values. Then we used the following syntax to create a for-each loop:
for (String bird: birds) { }
This statement loops through every item in the birds array.
Then, we printed out each item in the array using System.out.println()
.
Print a Multidimensional Array
A multidimensional array is an array with two dimensions which are represented by rows and columns. When you’re working with a multidimensional array, you may decide that you want to print its contents to the console.
We can accomplish this task using the Arrays.deepToString()
method, which is part of the Java Arrays library.
Suppose we have a multidimensional array that stores a list of our favorite books, sorted by genre. The first row in our array stores the names of our favorite business books; the next row stores the names of our favorite self-help books. We could use the following code to print out the contents of our multidimensional array:
import java.util.Arrays; class PrintBooks { public static void main(String[] args) { String[][] books = { {"The Secrets of Sand Hill Road", "The Upstarts"}, {"Atomic Habits", "How to Win Friends and Influence People"} }; System.out.println(Arrays.deepToString(books)); } }
Our code returns:
[[The Secrets of Sand Hill Road, The Upstarts], [Atomic Habits, How to Win Friends and Influence People]]
As you can see, our code printed out the contents of our multidimensional array. Let’s break down how our program works.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
First we declared a multidimensional array—called books—that stores two rows. The first row stores a list of our favorite business books, and the second row stores a list of our favorite self-help books.
Then we use the Arrays.deepToString()
method to convert the contents of books into a readable format. Finally, we print the result of the deepToString()
method to the console using System.out.println()
.
Conclusion
Printing an array is a common operation when you’re working with arrays in Java.
This tutorial discussed, using examples, the three main approaches used to print an array in Java: a for-each loop, the Arrays.toString()
method, and the Arrays.deepToString()
method. The last of these—Arrays.deepToString()
—is for multidimensional arrays.
Now you have the knowledge you need to start printing arrays in Java like a pro!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.