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[])](<https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#toString-java.lang.Object:A->)
or [Arrays.deepToString(Object[])](<https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#deepToString-java.lang.Object:A->)
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()](<http://stackoverflow.com/documentation/java/145/object-class-methods/568/tostring-method#t=201607222047045336269>)
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]