java.util.Arrays toString()
Description
Notes:
- The toString() method is effective only to one dimensional array. If you want to get the string representation of multi-dimensional array, the deepToString() method suits it best.
Method Syntax
public static String toString(datatype[] a)
Method Returns
The toString() method returns a string representation of a.
Compatibility
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.
package com.javatutorialhq.java.examples; 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[]{ "Alfred","Beth","Stan" }; // get the String representation of String array System.out.println("******Multi dimensional array******"); System.out.println(Arrays.toString(names)); // 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******"); System.out.println(Arrays.toString(value)); } }
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.