Arrays to a String

Download java eBook

Example

Java SE 5

Since Java 1.5 you can get a String representation of the contents of the specified array without iterating over its every element. Just use Arrays.toString(Object[]) or Arrays.deepToString(Object[]) for multidimentional arrays:

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

int[][] arr = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
System.out.println(Arrays.deepToString(arr));  // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Arrays.toString() method uses Object.toString() method to produce String values of every item in the array, beside primitive type array, it can be used for all type of arrays. For instance:

public class Cat { /* implicitly extends Object */
    @Override
    public String toString() {
      return "CAT!";
    }
}

Cat[] arr = { new Cat(), new Cat() };
System.out.println(Arrays.toString(arr));        // [CAT!, CAT!]

If no overridden toString() exists for the class, then the inherited toString() from Object will be used. Usually the output is then not very useful, for example:

public class Dog {
    /* implicitly extends Object */
}

Dog[] arr = { new Dog() };
System.out.println(Arrays.toString(arr));        // [Dog@17ed40e0]

Stats

Contributors: 9
2016-08-03
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook