GuidesHow to Print an Array in Java

How to Print an Array in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Printing an array in Java is not as straightforward as it is in some other programming languages. The standard method of printing objects does not produce the results you might expect. To overcome this, there are several other methods we can employ to print the values stored in an array. We will be looking at several code examples showcasing how this can be achieved.

Read: How to Create a Java ArrayList Class

If you have ever tried to print an array in Java using the System.out.println() method, then you will know that it is not so simple; using the standard print function on an array returns a reference to the array object we are trying to print – essentially printing out the equivalent to class name @ object hash code.

If you have not tried to print an array using System.out.println(), try out the following code to get an idea of what happens when you do:

 
class Main { 
  public static void main(String args[]) {
            	int[] testArray = {4, 8, 15, 16, 23, 42};
            	System.out.println("The results of printing our array values:");
            	System.out.println(testArray);
            	 
            	  }
}

In this code, we first create our Main class and then create an array named testArray that will hold some integer values. Next, we create two print statements. The first is designed to print some simple text that will output “The results of printing our array values:” to the monitor. The second print statement is designed to print the stored values in our array. However, as described above, using the System.out.println() method will not give us the results we expect. As you can see when you run the code example, instead of the output being: 4, 8, 15, 16, 23, 42, we get this output instead:

The results of printing our array values:
[I@76ed5528

Again, this is a reference to the class name and the object’s hash code. Not at all what we want in this instance.

Printing Arrays in Java Using For Loops

For loops are used when we want to execute a block of code until a given condition is met. This serves many purposes in a program, but for our example, we want to use the For loop to iterate – or repeat – through the values in our array until all of the items have been printed out. This method is the most common way to print array values in Java. Here is an example of how to use the for loop to print an array in Java:

class Main { 
  public static void main(String args[]) {
            	int[] testArray = {4, 8, 15, 16, 23, 42};
            	System.out.println("Printing array values with a for loop:");
            	for(int i=0;i<testArray.length;i++)  
System.out.println(testArray[i]);
            	 
            	  }
}
<\pre>

In this code, we start at element or item position [0], which is the first object in our array – or, in this case, the value 4. We then use the incrementer or i++ to tell Java that we want to move incrementally through all of the values that are in the array. The result of this program if you run it in your IDE or code editor:

Printing array values with a for loop:
4
8
15
16
23
42

How to Use the For Each Loop on Arrays in Java

Another option you can use to print the values in an array in Java is the For-each loop. You may also hear people refer to it as the Enhanced For loop on occasion. Whatever moniker you choose, the For-each look works like the regular For loop with the exception that For-each loops automatically increment through an array. This makes For-each loops a little more readable and clean from a coding perspective. However, they are technically a little more resource intensive. Additionally, you cannot decrement or walk backwards through an array with a For-each loop, so always keep that in mind when deciding which type of loop to use.

Here is a code example showing how to use the For-each loop to print an array in Java:

class Main { 
  public static void main(String args[]) {
            	int[] testArray = {4, 8, 15, 16, 23, 42};
            	System.out.println("Printing array values with a for-each loop:");
            	  for(int i : testArray){ 
     System.out.println(i); 
            	  
            	  }
            	 }
}

As you can see, the above code is much easier to write, easier to read, and less prone to errors than the regular For loop. Here is the output of running this code in your Integrated Development Environment:

Printing array values with a for-each loop:
4
8
15
16
23
42

Print Java Arrays using Arrays.toString()

If you do not want to use a loop to print out the values in an array, you can use Java’s built-in toString() method. Since data types in Java are all technically classes that inherit from java.lang.Object, we get the benefit of the toString() method for any data type – incuding arrays – that we create.

While using the toString() method is fairly simple, it does have its drawbacks. To see those drawbacks, let’s run the following code example showing how to use Arrays.toString() on an array in Java in our code editor:

import java.util.Arrays; 
class Main { 
  public static void main(String args[]) {
            	int[] testArray = {4, 8, 15, 16, 23, 42};
            	System.out.println("Printing array values:");
            	 System.out.println(Arrays.toString(testArray));
            	 
            	  }
            	
}

This code starts by importing the java.util.Arrays class, which is necessary to use the Array.toString() method, so always be certain to import the class. The result of running this code is:

Printing array values:
[4, 8, 15, 16, 23, 42]

As you can see from the output, this method of printing an array may not be suitable for all purposes, as it outputs the comma-delineation as well as the square brackets encasing the array values. Because of this, it is mostly useful when you want to show a representation of the values in an array versus the values themselves.

Another possible problem with this method of printing arrays is the fact that you can only use the toString() method on one-dimensional arrays. For nested arrays and two-dimensional arrays, you need to use the deepToString() method, which we will cover in a later article where we discuss multi-dimensional arrays, as there is not enough space in this article to do the topic justice.

Other Methods of Printing Arrays in Java

In this tutorial for developers we looked at three of the primary ways to print out the values of an array in Java. We started off by eliminating System.out.println(), because it only prints out a reference to the objects in an array. Since we want the actual values, we instead used a For loop and an enhanced for loop, which is better known as a For-each loop. Finally, we wrapped things up by learning how to use the built-in Arrays.toString() method, which is only useful on one-dimensional arrays.

Other methods do exist that allow programmers to print the values of an array. In addition to the methods within this tutorial, you can also use:

  • The Java Iterator Interface
  • The Java Stream API or Java Streams
  • Convert your array to a list
  • The Java Arrays.asList() method

We will cover these additional methods in a future article, so be certain to keep an eye out or check back here frequently.

Read More Java Tutorials

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories