Appearance
What's the simplest way to print a Java array?
There are several ways to print an array in Java. Here are a few options:
- Using a loop:
java
int[] array = {1, 2, 3, 4, 5};
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}- Using the
Arrays.toString()method:
java
import java.util.Arrays;
int[] array = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(array));- Using the
String.join()method (Java 8 or later):
java
int[] array = {1, 2, 3, 4, 5};
System.out.println(String.join(" ", Arrays.stream(array).mapToObj(String::valueOf).toArray(String[]::new)));For most use cases, Arrays.toString() is the standard and most concise approach. Note that it outputs elements with brackets and commas (e.g., [1, 2, 3]), while the loop and String.join() methods produce space-separated values. For multi-dimensional arrays, use Arrays.deepToString() instead.