Arrays.toString()
Returns the contents of an array as a string like [1, 2, 3].
Available since: Java 5
Syntax
static String toString(int[] a)Parameters
| Parameter | Type | Description |
|---|---|---|
| a | int[], Object[], … | An array of primitives or objects. |
Return value
StringA string with the elements in square brackets, separated by commas.
Examples
Printing an array directly shows an address, Arrays.toString() shows the elements:
void main() {
int[] numbers = {3, 1, 2};
IO.println(Arrays.toString(numbers));
String[] words = {"a", "b"};
IO.println(Arrays.toString(words));
}Output:
[3, 1, 2]
[a, b]A two-dimensional array needs deepToString():
void main() {
int[][] grid = {{1, 2}, {3, 4}};
IO.println(Arrays.deepToString(grid));
}Output:
[[1, 2], [3, 4]]Notes
IO.println(numbers) prints something like [I@1b6d3586 — the type and hash of the object, not its contents. It is a very common beginner mistake. For null the method returns the string "null".
See also
- Arrays.sort() — Sorts an array in place — in ascending order or by a given comparator.
- array.length — The length of an array — the number of elements. A field, not a method: no parentheses.
- String.join() — Joins strings with a separator.
Related recipes
In the tutorial
- The Arrays class — Utilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.