Java - Best way to print 2D array?

Chip Goon Lewin picture Chip Goon Lewin · Oct 29, 2013 · Viewed 288.3k times · Source

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();
}

Answer

Prabhakaran Ramaswamy picture Prabhakaran Ramaswamy · Oct 29, 2013

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));