How to Print Array as String in Java

1. Introduction

In Java, directly printing an array using the System.out.println() method does not display the array's contents but rather its internal memory address. To print an array as a string that represents its contents, Java provides several methods, including using the Arrays.toString() method for one-dimensional arrays and Arrays.deepToString() for multi-dimensional arrays. This blog post will demonstrate how to print both one-dimensional and multi-dimensional arrays as strings in Java, providing clear, human-readable output.

2. Program Steps

1. Declare and initialize both one-dimensional and multi-dimensional arrays.

2. Use the Arrays.toString() method to print the one-dimensional array as a string.

3. Use the Arrays.deepToString() method to print the multi-dimensional array as a string.

4. Display the results.

3. Code Program

import java.util.Arrays;

public class PrintArrayAsStringExample {
    public static void main(String[] args) {
        // Step 1: Declare and initialize arrays
        int[] oneDimensionalArray = {1, 2, 3, 4, 5};
        int[][] multiDimensionalArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

        // Step 2: Print one-dimensional array as a string
        System.out.println("One-dimensional array: " + Arrays.toString(oneDimensionalArray));

        // Step 3: Print multi-dimensional array as a string
        System.out.println("Multi-dimensional array: " + Arrays.deepToString(multiDimensionalArray));


One-dimensional array: [1, 2, 3, 4, 5]
Multi-dimensional array: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


1. The program begins by declaring and initializing a one-dimensional array, oneDimensionalArray, and a multi-dimensional array, multiDimensionalArray, with sample values to demonstrate the printing methods.

2. To print the one-dimensional array as a string, the Arrays.toString(oneDimensionalArray) method is used. This method takes the array as an argument and returns a string representation of the array's elements, enclosed in square brackets and separated by commas.

3. For the multi-dimensional array, the Arrays.deepToString(multiDimensionalArray) method is utilized. Similar to toString(), it provides a string representation of each element in a multi-dimensional array, including nested arrays, ensuring a human-readable format for arrays of any depth.

4. The output shows the string representations of both a one-dimensional and a multi-dimensional array, demonstrating straightforward methods to print arrays in Java in a readable format, without resorting to manually iterating over the elements and building the string representation from scratch.