java.util.Arrays toString()


On this document we will be showing a java example on how to use the toString() method of Arrays Class. This method is overloaded in such a way that all possible data type is handled. Basically the toString() method returns a string representation of the contents of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters “, ” (a comma followed by a space). Elements are converted to strings as by String.valueOf(boolean). Returns “null” if a is null.


Method Syntax

public static String toString(datatype[] a)

Method Returns

The toString() method returns a string representation of a.


Requires Java 1.5 and up

Java Arrays toString() Example

Below is a java code demonstrates the use of toString() method of Arrays class. The example presented might be simple however it shows the behavior of the toString() method.


import java.util.Arrays;

 * A java example source code to demonstrate
 * the use of toString() method of Arrays class

public class ArraysToStringExample {

	public static void main(String[] args) {

		// initialize a new String array
		String[] names = new String[]{
		// get the String representation of String array
		System.out.println("******Multi dimensional array******");
		// get String representation multi dimensional array		
		int[][] value = new int[2][2];		
		value[0][0] = 1;
		value[0][1] = 2;
		value[1][0] = 3;
		value[1][1] = 4;			
		System.out.println("******Multi dimensional array******");

The above java example source code demonstrates the use of toString() method of Arrays class.We simply declare a new String Array that correspond to student names. Then we printed it using the toString() method which works perfectly fine. However on the latter part we have also initialized a 2 dimensional int array. As you would have noticed, the printing of data will not works the same way as the first one. Instead of printing the string representation of array, we would be getting a String representation of each object inside the array which is in turn to be the hashcode of each elements. If you want to print it better, you can use the deepToString() method.

Sample Output

Below is the sample output when you run the above example.

Arrays toString() example output