Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

1.8. Printing an Array

1.8.1. Problem

You need to print the contents of an array.

1.8.2. Solution

Use ArrayUtils.toString() to print the contents of an array. This method takes any array as an argument and prints out the contents delimited by commas and surrounded by brackets:

int[] intArray = new int[] { 2, 3, 4, 5, 6 };
int[] multiDimension = new int[][] { { 1, 2, 3 }, { 2, 3 }, {5, 6, 7} };
System.out.println( "intArray: " + ArrayUtils.toString( intArray ) );
System.out.println( "multiDimension: " + ArrayUtils.
toString( multiDimension ) );

This example takes two arrays and prints them out using ArrayUtils.toString( ):

intArray: {2,3,4,5,6}
multiDimension: {{1,2,3},{2,3},{5,6,7}}

1.8.3. Discussion

This simple utility can be used to print the contents of an Object[], substituting an object for a null element:

String[] strings = new String[] { "Blue", "Green", null, "Yellow" };
System.out.println( "Strings: " + ArrayUtils.toString( strings, "Unknown" );

This example prints the strings array, and when ArrayUtils encounters a null element, it will print out "Unknown":

Strings: {Blue,Green,Unknown,Yellow}

This utility comes in handy when you need to print the contents of a Collection for debugging purposes. If you need to print out the contents of a Collection, convert it to an array, and pass that array to ArrayUtils.toString():

List list = new ArrayList( );
list.add( "Foo" );
list.add( "Blah" );
System.out.println( ArrayUtils.toString( list.toArray( ) ) );

Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.