- How to print an array in java
- Java Array Programs
- How to print array in java
- Using Arrays.toString()
- Using deepToString() method
- Using Java 8 Stream API
- Using for loop
- Using for-each loop
- Print array in reverse order in java
- Print array with custom objects
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- Create Array from 1 to n in Java
- How to Print 2D Array in Java
- Return Empty Array in Java
- How to Write Array to File in Java
- How to Initialize an Array with 0 in Java
- Set an Array Equal to Another Array in Java
How to print an array in java
This post will detail out different methods of printing array in java.
Method 1 : Using Arrays.toString method
java.util.Arrays class has a toString method which takes an array as argument and returns a string which is a representation of the array.
This representation is meaningful and consists of elements of array surrounded by square brackets.
Example,
import java.util.Arrays; public class ArrayToStringConverter { public static void main(String[] args) { String[] array = {"java", "python", "angular"}; System.out.println(Arrays.toString(array)); } }
import java.util.Arrays; public class ArrayToStringConverter < public static void main(String[] args) < String[] array = ; System.out.println(Arrays.toString(array)); > >
Method 2 : Using Arrays.asList method
java.util.Arrays class has a asList method which takes an array as argument and returns java.util.List object populated with the elements of array.
This list can be directly printed as shown below.
import java.util.Arrays; import java.util.List; public class ArrayToStringConverter { public static void main(String[] args) { String[] array = {"java", "python", "angular"}; // convert array to list List list = Arrays.asList(array); System.out.println(list); } }
import java.util.Arrays; import java.util.List; public class ArrayToStringConverter < public static void main(String[] args) < String[] array = ; // convert array to list List list = Arrays.asList(array); System.out.println(list); > >
The reason that the list prints the above output is that the super class of all list implementations, that is, java.util.AbstractCollection has an overridden toString method which returns the list in string format as printed in the output.
Method 3 : Using join method of String
java 8 introduced a new method join in java.lang.String class.
This is a static method which takes two arguments;
second argument is the array of String elements, and
first argument is the delimiter or the separator with which the elements of array are joined.
This method iterates over the array elements, combines them with the supplied delimiter and returns the combined string.
Example,
import java.util.Arrays; public class ArrayToStringConverter { public static void main(String[] args) { String[] array = {"java", "python", "angular"}; // join array elements with a comma String joinedString = String.join(", ", array); System.out.println(joinedString); } }
import java.util.Arrays; public class ArrayToStringConverter < public static void main(String[] args) < String[] array = ; // join array elements with a comma String joinedString = String.join(", ", array); System.out.println(joinedString); > >
With this approach, you can customize the separator between array elements.
Thus, if you want the array elements to be separated by a space, then supply a space as the first argument to the join method as shown below.
String joinedString = String.join(” “, array);
Method 4 : Using streams in java 8
java 8 also introduced the concept of streams which can be used to print a string array.
Example code which can be used to print array contents is given below.
import java.util.Arrays; import java.util.stream.Stream; public class ArrayToStringConverter { public static void main(String[] args) { String[] array = {"java", "python", "angular"}; Arrays.asList(array).stream().forEach(s ->; System.out.print(s + " ")); } }
import java.util.Arrays; import java.util.stream.Stream; public class ArrayToStringConverter < public static void main(String[] args) < String[] array = ; Arrays.asList(array).stream().forEach(s ->; System.out.print(s + » «)); > >
Above code converts array to a list using asList method and then creates a stream of this list using stream method.
This stream is then iterated using forEach method. In every iteration, the current array element is received into the lamba expression provided to forEach as argument.
Output is
Above code prints array elements separated with an empty space.
If you want the elements to be separated by a comma, then modify the forEach body as shown below.
Arrays.asList(array).stream().forEach(s ->; System.out.print(s + “, “));
Method 5 : Using for loop
This is a traditional method which iterates over an array using a for loop and prints the current element in every iteration.
This method is not a one-liner solution to print array.
Example,
public class ArrayToStringConverter { public static void main(String[] args) { String[] array = {"java", "python", "angular"}; // iterate over array for(String element: array) { System.out.print(element + " "); } } }
With this approach also, you can change the separator between elements of the array.
For any other method known to you, add in the comment box below.
Hit the clap below if you liked the article. Keep visiting.
Java Array Programs
- Find length of array in java
- 5 ways to print array meaningfully
- Create a mirror image(inverse) of a 2d array
- 5 ways to find sum of array elements
- 2 ways to calculate median from array
- Search array element with Binary Search in 4 ways
- Check if array contains a value in 5 ways
- Check if an array is Palindrome in 2 ways
- Reverse an array in 6 ways
- Generate array of random integers using java 8 streams
- Check if Object is Array in java
How to print array in java
In this post, we will see how to print array in java.
There are multiple ways to print an array. Let’s go through few ways to print array in java.
Using Arrays.toString()
You can use Arrays.toString() method to print array in java. This is simplest ways to print an array.
Arrays.toString() returns string object.This String contains array in string format.
Let us understand with the code
Using deepToString() method
Basically Arrays.toString() works fine for a 1-dimensional arrays,but it won’t work for multidimensional arrays.
Let’s say we have 2-dimensional array as shown
1 2 3
4 5 6
7 8 9
To convert multidimensional arrays to string, you can use Arrays.deepToString() method. This is how you can print 2D array in java.
Using Java 8 Stream API
In java 8, you can convert array to Stream and print array with Stream’s foreach() method.
Arrays . stream ( string2DArray ) . flatMap ( str — > Arrays . stream ( str ) ) . forEach ( System . out : : println ) ;
Arrays . stream ( int2DArray ) . flatMapToInt ( i — > Arrays . stream ( i ) ) . forEach ( System . out : : println ) ;
As you can see we have seen how to print String array and Integer array in java using Stream.
Using for loop
You can iterate the array using for loop and print elements of array in java.
Using for-each loop
For each works same as for loop but with differs syntax.
Print array in reverse order in java
You can iterate the array using for loop in reverse order and print the element. This will print array in reverse order.
Print array with custom objects
In case, you have custom object in the array, then you should override toString() method in custom class, else it will give you unexpected results.
Let’s see with the help of example
Create a simple class named Color.java
Create main class named PrintArrayOfColors.java
If you notice, we don’t have toString() method in Color class, that’s why it is calling Object’s toString() method and we are not able to see meaningful results.
We need to override toString() method in Color class and we will get informative output.
When you run PrintListOfColorsMain again, you will get below output:
As you can see, we have much meaningful output now.
That’s all about how to print array in java.
Was this post helpful?
Share this
Next Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers
Related Posts
Author
Related Posts
Create Array from 1 to n in Java
Table of ContentsIntroductionArray in JavaCreate Array from 1 to N in JavaUsing Simple For loop in JavaUsing IntStream.range() method of Stream API in JavaUsing IntStream.rangeClosed() method of Stream API in JavaUsing IntStream.iterate() method of Stream API in JavaUsing the Stream class of Stream API in JavaUsing Arrays.setAll() method in JavaUsing Eclipse Collections Framework in JavaUsing […]
How to Print 2D Array in Java
Table of ContentsIntroductionWhat is a 2-dimensional array or matrix in java?How to print a 2D array in java?Simple Traversal using for and while loopUsing For-Each Loop to print 2D Array in JavaArrays.toString() method to print 2D Array in JavaArrays.deepToString() method to print 2D Array in JavaUsing Stream API in Java 8 to print a 2D […]
Return Empty Array in Java
Table of ContentsWhat Is the Need to Return an Empty Array?How Do You Return Empty Array in Java?Using Curly Braces to Return Empty Array in JavaUsing Anonymous Array Objects – New Int[0] to Return Empty Array Using Empty Array Declaration to Return Empty Array in JavaUsing Apache Commons Library – Array Utils Package to Return Empty […]
How to Write Array to File in Java
Table of ContentsWays to Write Array to File in JavaUsing BufferWriterUsing ObjectOutputStream In this post, we will see how to write array to file in java. Ways to Write Array to File in Java There are different ways to write array to file in java. Let’s go through them. Using BufferWriter Here are steps to […]
How to Initialize an Array with 0 in Java
Table of ContentsArraysInitializing Newly Created ArrayUsing Default Initialization of Arrays in JavaUsing Initialization After DeclarationUsing Simultaneous Initializing and Declaration of ArrayUsing Reflection in JavaInitializing Existing ArrayUsing the Arrays.fill() Function of JavaUsing the for LoopUsing Reassignment From Another ArrayUsing Collections.nCopies() Function of JavaInitializing User-Defined Object ArrayConclusion This article discusses the arrays and different ways to initialize […]
Set an Array Equal to Another Array in Java
Table of ContentsSetting an Array Variable Equal to Another Array VariableSet an Array Equal to Another Array in Java Using the clone() MethodSet an Array Equal to Another Array in Java Using the arraycopy() MethodSet an Array Equal to Another Array in Java Using the copyOf() MethodSet an Array Equal to Another Array in Java […]