Best and Simplest ways to print Java Array

Many time printing arrays in Java are required to logging and debugging purpose. In Java provides Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays (a nested array) to formatting simple arrays into printable strings.

Example of printing a simple array:

String names[] = new String[] {"ssp","anu","kirti","shaurya"};
System.out.println(names);
System.out.println(Arrays.toString(names));

the output of above code is given below:

[Ljava.lang.String;@2a139a55
[ssp, anu, kirti, shaurya]

Example of printing nested array:

String names[][] = new String[][] { { "ssp", "anu", "kirti", "shaurya" }, { "Ram", "Shyam" } };
System.out.println(Arrays.toString(names));
System.out.println(Arrays.deepToString(names));

the output of above code is given below:

[[Ljava.lang.String;@2a139a55, [Ljava.lang.String;@15db9742]
[[ssp, anu, kirti, shaurya], [Ram, Shyam]]

Same used for other primitive types array like for int

int[] integers = new int[] {1,2,3,4,5};
System.out.println(Arrays.toString( integers));

output:

[1, 2, 3, 4, 5]

Java 8 and above we can use aggregate operations and a lambda expression to print arrays .

int[] integres = new int[] {1,2,3,4,5};
Arrays.stream(integres).forEach(System.out::println);

output:

1
2
3
4
5

Since Java 8, we can use the join() method of the String class to print out array elements of the string only, without the brackets, and separated by a delimiter of choice, look at the example below:

String[] data = {"i", "am", "anupama!"};
String delimiter = " + ";
String str = String.join(delimiter, data);
System.out.println(str);

output:

i + am + anupama!

System.out.println prints List objects as println calls objects toString method, for example:

List<Integer> data = new ArrayList<>();
data.add(0);
data.add(2);
System.out.println(data);

output:

[0, 2]

You can also use:

System.out.println(Arrays.asList(array));

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.