[java] Java - Best way to print 2D array?

I was wondering what the best way of printing a 2D array was. This is some code that I have and I was just wondering if this is good practice or not. Also correct me in any other mistakes I made in this code if you find any. Thanks!

int rows = 5;
int columns = 3;

int[][] array = new int[rows][columns];

for(int i = 0; i<rows; i++)
    for(int j = 0; j<columns; j++)
        array[i][j] = 0;

for(int i = 0; i<rows; i++)
{
    for(int j = 0; j<columns; j++)
    {
        System.out.print(array[i][j]);
    }
    System.out.println();
}

This question is related to java arrays printing

The answer is


There is nothing wrong with what you have. Double-nested for loops should be easily digested by anyone reading your code.

That said, the following formulation is denser and more idiomatic java. I'd suggest poking around some of the static utility classes like Arrays and Collections sooner than later. Tons of boilerplate can be shaved off by their efficient use.

for (int[] row : array)
{
    Arrays.fill(row, 0);
    System.out.println(Arrays.toString(row));
}

From Oracle Offical Java 8 Doc:

public static String deepToString(Object[] a)

Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings.


Adapting from https://stackoverflow.com/a/49428678/1527469 (to add indexes):

System.out.print(" ");
for (int row = 0; row < array[0].length; row++) {
    System.out.print("\t" + row );
}
System.out.println();
for (int row = 0; row < array.length; row++) {
    for (int col = 0; col < array[row].length; col++) {
        if (col < 1) {
            System.out.print(row);
            System.out.print("\t" + array[row][col]);
        } else {

            System.out.print("\t" + array[row][col]);
        }
    }
    System.out.println();
}

You can print in simple way.

Use below to print 2D array

int[][] array = new int[rows][columns];
System.out.println(Arrays.deepToString(array));

Use below to print 1D array

int[] array = new int[size];
System.out.println(Arrays.toString(array));

With Java 8 using Streams and ForEach:

    Arrays.stream(array).forEach((i) -> {
        Arrays.stream(i).forEach((j) -> System.out.print(j + " "));
        System.out.println();
    });

The first forEach acts as outer loop while the next as inner loop


Two-liner with new line:

for(int[] x: matrix)
            System.out.println(Arrays.toString(x));

One liner without new line:

System.out.println(Arrays.deepToString(matrix));

@Ashika's answer works fantastically if you want (0,0) to be represented in the top, left corner, per normal CS convention. If however you would prefer to use normal mathematical convention and put (0,0) in the lower left hand corner, you could use this:

LinkedList<String> printList = new LinkedList<String>();
for (char[] row: array) {
    printList.addFirst(Arrays.toString(row));;
}
while (!printList.isEmpty())
    System.out.println(printList.removeFirst());

This used LIFO (Last In First Out) to reverse the order at print time.


I would prefer generally foreach when I don't need making arithmetic operations with their indices.

for (int[] x : array)
{
   for (int y : x)
   {
        System.out.print(y + " ");
   }
   System.out.println();
}

class MultidimensionalArray {
    public static void main(String[] args) {

        // create a 2d array
        int[][] a = {
                {1, -2, 3},
                {-4, -5, 6, 9},
                {7},
        };

        // first for...each loop access the individual array
        // inside the 2d array
        for (int[] innerArray: a) {
            // second for...each loop access each element inside the row
            for(int data: innerArray) {
                System.out.println(data);
            }
        }
    }
}

You can do it like this for 2D array


That's the best I guess:

   for (int[] row : matrix){
    System.out.println(Arrays.toString(row));
   }

Simple and clean way to print a 2D array.

System.out.println(Arrays.deepToString(array).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));

Try this,

for (char[] temp : box) {
    System.err.println(Arrays.toString(temp).replaceAll(",", " ").replaceAll("\\[|\\]", ""));
}

System.out.println(Arrays.deepToString(array)
                         .replace("],","\n").replace(",","\t| ")
                         .replaceAll("[\\[\\]]", " "));

You can remove unwanted brackets with .replace(), after .deepToString if you like. That will look like:

 1  |  2  |  3
 4  |  5  |  6
 7  |  8  |  9
 10 |  11 |  12
 13 |  15 |  15

|1 2 3|
|4 5 6| 

Use the code below to print the values.

System.out.println(Arrays.deepToString());

Output will look like this (the whole matrix in one line):

[[1,2,3],[4,5,6]]

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to printing

How do I print colored output with Python 3? Print a div content using Jquery Python 3 print without parenthesis How to find integer array size in java Differences Between vbLf, vbCrLf & vbCr Constants Printing variables in Python 3.4 Show DataFrame as table in iPython Notebook Removing display of row names from data frame Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window Print a div using javascript in angularJS single page application