How to print an array
Short answer
Arrays.toString() turns an array into a readable string:
void main() {
int[] numbers = {5, 3, 8};
IO.println(Arrays.toString(numbers));
}Output:
[5, 3, 8]A 2D array
An array of arrays needs Arrays.deepToString():
void main() {
int[][] grid = {{1, 2}, {3, 4}};
IO.println(Arrays.deepToString(grid));
}Output:
[[1, 2], [3, 4]]A custom format
Join strings with String.join(), and anything else with a stream:
void main() {
String[] names = {"Anna", "Oleg"};
double[] prices = {1.5, 20.0};
IO.println(String.join(" / ", names));
IO.println(Arrays.stream(prices).mapToObj(p -> p + " €").collect(Collectors.joining(", ")));
}Output:
Anna / Oleg
1.5 €, 20.0 €A table
A 2D array is easy to print row by row:
void main() {
int[][] grid = {{1, 2, 3}, {4, 5, 6}};
for (int[] row : grid) {
IO.println(Arrays.stream(row).mapToObj(n -> "%3d".formatted(n)).collect(Collectors.joining()));
}
}Output:
1 2 3
4 5 6Common mistake
Printing an array directly. Arrays do not override toString(), so you get the type and a hash code:
void main() {
int[] numbers = {5, 3, 8};
IO.println(numbers);
}Output:
[I@1786f9d5The number after @ will be different for you.
Functions used in this recipe
- Arrays.toString() — Returns the contents of an array as a string like [1, 2, 3].
- String.join() — Joins strings with a separator.