How To Print An Array In Java - CodeGym
Maybe your like
Why is there a Need to Print Arrays in Java?
Java provides Array data structure to store different elements of the same data type. The elements are stored in contiguous memory. To display the similar contents of the array, the elements are needed to be printed.Methods to Print an Array in Java
There are a bunch of different ways to print an array in Java. You can use manual traversals using for loops or opt for any standard library methods to do the same. Here is a list of ways to print arrays in Java that we will be exploring in this article.- for loop
- for each loop
- Arrays.toString() method
- Arrays.toList() method
- Java Iterators
Method I - Printing array using for loop
This is the simplest way, to begin with. Here’s how you can do it. public class printArrayMethod1 { public static void main(String[] args) { String[] monthsOfTheYear = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; System.out.println("Months of the year are as follows:"); // Method I - Printing array using for loop for (int i = 0; i < monthsOfTheYear.length; i++) { System.out.println(monthsOfTheYear[i]); } } }Output
Months of the year are as follows: January February March April May June July August September October November DecemberMethod II - Printing array using for each loop
For each loop is another form of the basic for loop. Here you do not need to initialize and increment the loop iterator. The loop directly traverses the elements of the array. Making it simpler to use. public class printArrayMethod2 { public static void main(String[] args) { String[] monthsOfTheYear = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; System.out.println("Months of the year are as follows:"); // Method II - Printing array using for each loop for (String month : monthsOfTheYear) { System.out.println(month); } } }
Output
Months of the year are as follows: January February March April May June July August September October November DecemberMethod III - Using Standard Library Arrays
The Java Arrays.toString() method is provided by the java.util.Arrays class. It takes an array as an input parameter. The array can be of any primitive type. Later, the array is converted to a String before printing on the console. import java.util.Arrays; public class printArrayMethod3 { public static void main(String[] args) { String[] monthsOfTheYear = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; System.out.println("Months of the year are as follows:"); // Method III - Using Standard Library Arrays System.out.println(Arrays.toString(monthsOfTheYear)); } }Output
As you can see in the output, the whole contiguous array elements are printed comma-separated on the console. Months of the year are as follows: [January, February, March, April, May, June, July, August, September, October, November, December]Method IV - Using Standard Library Arrays asList Method
The Java Arrays.asList() method is also provided by the java.util.Arrays class. A primitive data type array can be passed to it as a parameter. Later, the list type view of the input array is printed on the console. import java.util.Arrays; public class printArrayMethod4 { public static void main(String[] args) { String[] monthsOfTheYear = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; System.out.println("Months of the year are as follows:"); // Method IV - Using Standard Library Arrays asList Method System.out.println(Arrays.asList(monthsOfTheYear)); } }Output
Months of the year are as follows: [January, February, March, April, May, June, July, August, September, October, November, December]Method V - Using Iterators to traverse the Array
This is a little advanced method. You may like to get acquainted with the Collections Framework in Java before proceeding. Java provides an interface called “iterator” present in java.util package. Iterator object is used to traverse over the objects of the Collection class. Therefore, in the following example, the array needs to be converted to a “List” before using the iterator. import java.util.Arrays; import java.util.Iterator; public class printArrayMethod5 { public static void main(String[] args) { String[] monthsOfTheYear = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; System.out.println("Months of the year are as follows:"); // Method V - Using Iterators to traverse the Array Iterator<String> itr = Arrays.asList(monthsOfTheYear).iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } }Output
Months of the year are as follows: January February March April May June July August September October November December To reinforce what you learned, we suggest you watch a video lesson from our Java CourseYou’ve already got the hang of printing simple arrays using methods like Arrays.toString(), but things get trickier with multi-dimensional arrays. Luckily, Java has you covered with Arrays.deepToString(). This method is perfect for those times when you want to see the contents of nested arrays in all their glory. Let’s dive in and see how it works.
Why Arrays.deepToString() Is a Game Changer
The Arrays.toString() method only handles one-dimensional arrays gracefully. If you try to print a two-dimensional array with Arrays.toString(), you get something cryptic like [[I@6d06d69c, which isn’t exactly helpful. That’s where Arrays.deepToString() steps in to produce a human-readable representation of multi-dimensional arrays.
Here’s an example:
import java.util.Arrays; public class DeepToStringExample { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println(\"Using Arrays.toString():\"); System.out.println(Arrays.toString(matrix)); System.out.println(\"\\nUsing Arrays.deepToString():\"); System.out.println(Arrays.deepToString(matrix)); } }When you run this code, Arrays.toString() prints a bunch of memory addresses, while Arrays.deepToString() shows something like [[1, 2, 3], [4, 5, 6], [7, 8, 9]], which is much easier on the eyes.
Difference Between Arrays.toString() and Arrays.deepToString()
So what’s the real difference? Arrays.toString() is great for one-dimensional arrays but fails to display multi-dimensional arrays in a readable way. On the other hand, Arrays.deepToString() iterates through nested arrays and prints them in a more structured format.
In short, Arrays.toString() is your go-to for one-dimensional arrays. Once you’re dealing with nested arrays, Arrays.deepToString() is the hero you need.
Formatting Multi-Dimensional Arrays with Arrays.deepToString()
By default, Arrays.deepToString() prints everything on a single line. That might be good enough most of the time, but what if you want to make it really pop with custom formatting? Let’s see how we can break it down into multiple lines using a little trick with string manipulation. This is just one approach, so feel free to adapt it to your taste.
import java.util.Arrays; public class CustomFormatExample { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; String rawOutput = Arrays.deepToString(matrix); // rawOutput looks like [[1, 2, 3], [4, 5, 6], [7, 8, 9]] // Let's replace some characters to format it nicely String formatted = rawOutput .replace(\"],\", \"],\\n\") .replace(\"[[\", \"[\\n[\") .replace(\"]]\", \"]\\n]\"); System.out.println(\"Formatted 2D Array:\\n\" + formatted); } } In this example, we’re taking the output from Arrays.deepToString() and adding newlines. The result is a cleaner, more visually appealing multi-line output. This is just a simple approach—feel free to get creative with your formatting.
Conclusion
Here was a quick overview of different methods for printing the elements of an array. These examples were based on String data type. However, you are encouraged to experiment with different primitive and non-primitive data types too. Initially, your code can have bugs or can have runtime exceptions but these are the learning curves you need to work on. Feel free to rewind wherever you get stuck. Till then, keep practicing and keep growing.Tag » How To Print An Array In Java
-
What's The Simplest Way To Print A Java Array? - Stack Overflow
-
Java Program To Print An Array - Programiz
-
Java Program To Write An Array Of Strings To The Output Console
-
How To Print Array With Elements In Java? [Solution + Example]
-
How To Print Array In Java - Javatpoint
-
Java Program To Print The Elements Of An Array - Javatpoint
-
Java Array Methods – How To Print An Array In Java - FreeCodeCamp
-
How To Print Elements Of An Array In Java - Software Testing Help
-
5 Methods To Print An Array In Java - TecAdmin
-
How To Print An Array In Java With Multiple Methods
-
How To Print An Array In Java - Linux Hint
-
Java Program To Print Elements Of Array - Tutorial Kart
-
How To Print Multi-dimensional Arrays In Java
-
How To Print An Array In Java