Java Language Arrays Arrays to a String

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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]


Got any Java Language Question?