How to Print Array as String in Java

In Java, there are several ways to print an array as a string. In this guide, we will learn some common methods to print an array as a string in Java.

1. Using Arrays.toString() for 1D Arrays

The Arrays.toString() method converts the array to a string, where each element is separated by commas and enclosed in square brackets.

Example:

import java.util.Arrays;

public class ArrayToString {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};

        // Convert the array to a string
        String arrayAsString = Arrays.toString(array);

        // Print the array as a string
        System.out.println("Array as String: " + arrayAsString);
    }
}

Output:

Array as String: [1, 2, 3, 4, 5]

2. Using Arrays.deepToString() for Multidimensional Arrays

For multidimensional arrays (e.g., 2D arrays), you can use Arrays.deepToString() to print the array as a string. This method handles nested arrays properly.

Example:

import java.util.Arrays;

public class MultiDimArrayToString {
    public static void main(String[] args) {
        int[][] array = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        // Convert the 2D array to a string
        String arrayAsString = Arrays.deepToString(array);

        // Print the 2D array as a string
        System.out.println("2D Array as String: " + arrayAsString);
    }
}

Output:

2D Array as String: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

3. Using String.join() for an Array of Strings

If you have an array of strings, you can use String.join() to concatenate them into a single string, with a delimiter of your choice.

Example:

public class StringArrayToString {
    public static void main(String[] args) {
        String[] array = {"Hello", "World", "Java", "8"};

        // Join the array elements into a single string with spaces
        String arrayAsString = String.join(" ", array);

        // Print the array as a string
        System.out.println("Array as String: " + arrayAsString);
    }
}

Output:

Array as String: Hello World Java 8

4. Using a Loop to Manually Build the String

You can also manually concatenate the elements of the array into a string using a loop. This gives you more control over the formatting.

Example:

public class ManualArrayToString {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};

        // Initialize an empty string builder
        StringBuilder result = new StringBuilder();

        // Append each element to the string builder
        for (int i = 0; i < array.length; i++) {
            result.append(array[i]);
            if (i < array.length - 1) {
                result.append(", "); // Add a comma and space between elements
            }
        }

        // Convert the string builder to a string
        String arrayAsString = result.toString();

        // Print the array as a string
        System.out.println("Array as String: " + arrayAsString);
    }
}

Output:

Array as String: 1, 2, 3, 4, 5

5. Using Stream API in Java 8+ for Primitive Arrays

For arrays of primitives, you can use the Stream API to convert the array to a string:

Example:

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class StreamArrayToString {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};

        // Convert the array to a string using streams
        String arrayAsString = IntStream.of(array)
                                        .mapToObj(String::valueOf)
                                        .collect(Collectors.joining(", "));

        // Print the array as a string
        System.out.println("Array as String: " + arrayAsString);
    }
}

Output:

Array as String: 1, 2, 3, 4, 5

Conclusion

These methods allow you to convert and print arrays as strings in Java, depending on the type of array and the desired format. Arrays.toString() and Arrays.deepToString() are the most straightforward methods for one-dimensional and multidimensional arrays, respectively, while String.join() and streams provide flexibility for formatting and custom output.

Comments