Print array content with Arrays.toString or Arrays.asList

When directly printing an array, it gives its element type and hashcode, which is not the desired result in most cases. A better way is to use java.util.Arrays.toString(), or Arrays.asList() method to print the string representation of the array.

This test method tries 2 ways of printing the content of a string array:

public final void testPrintArray() {
   final String[] names = {"Linux", "Mac OS X", "Windows", "Solaris", null};
   System.out.println("print names array directly: " + names);
   System.out.println("print names with Arrays.toString(): " + Arrays.toString(names));
   System.out.println("print names with Arrays.asList(): " + Arrays.asList(names));
   //but String.valueOf() won't print array content
   System.out.printf("print names with String.valueOf(): %s%n", String.valueOf(names));
Test output:
print names array directly: [Ljava.lang.String;@5122cdb6
print names with Arrays.toString(): [Linux, Mac OS X, Windows, Solaris, null]
print names with Arrays.asList(): [Linux, Mac OS X, Windows, Solaris, null]
print names with String.valueOf(): [Ljava.lang.String;@293e86f
Between the 2 methods, I find toString() is more natural. Arrays.toString() was introduced in Java 5, somewhat later than Arrays.asList().

Also note that a List can take null as element value, and its string representation is "null".


Apple Eye said...

You are writing good articles, why don't you add Android articles as well?

How to do in java said...

Arrays.asList() will bring performance overhead. Arrays.toString() is better fit. Also, Arrays.deepToString() is worth knowing.

Java dev said...

I think best way to print array in Java is by using Arrays.toString() and Arrays.deepToString(), similar to comparing arrays using equals and deepEquals

Steve Smith said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Course in Chennai

Java Online Training India

Paul Smith said...

Brill! I'm so thankful for your article, t;s useful and helpful for me! The process of custom writing can't be as easy as counting to five - you need to take this into account!