116

I was wondering what the best way of printing a 2D array in Java was?

I was just wondering if this code is good practice or not?
Also any other mistakes I made in this code if you find any.

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();
}
Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Chip Goon Lewin
  • 1,213
  • 3
  • 10
  • 6

14 Answers14

237

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));
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • 17
    The 2D version prints everything on a single line, which is not ok :( – Dang Manh Truong Mar 31 '17 at 02:52
  • 1
    @DangManhTroung then write a for loop with a print line. – JakeWilson801 Apr 25 '17 at 18:11
  • 58
    I know this is a little later, but this prints everything out on separate lines. [I took this from this so answer](https://stackoverflow.com/questions/12845208/how-to-print-two-dimensional-array-like-table#17423410) `System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n"));` – wanderer0810 Nov 15 '17 at 15:15
32

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

Simple and clean way to print a 2D array.

System.out.println(Arrays.deepToString(array).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));
matthewpliddy
  • 450
  • 5
  • 7
12

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));
}
ashika
  • 194
  • 3
  • 1
    This solution will print your array with (0,0) at the top left corner (which is the convention for most things in CS, such as GUI placement or Pixel location in an image). In many non-cs scenarios you would want (0,0) to be in the lower left corner, though, in which case a foreach loop will not work. – Max von Hippel Mar 03 '16 at 17:59
9

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));
suvojit_007
  • 1,690
  • 2
  • 17
  • 23
6

That's the best I guess:

   for (int[] row : matrix){
    System.out.println(Arrays.toString(row));
   }
Plcode
  • 223
  • 4
  • 8
5

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.

ZhaoGang
  • 4,491
  • 1
  • 27
  • 39
4
|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]]
Grzegorz Górkiewicz
  • 4,496
  • 4
  • 22
  • 38
Baseem
  • 41
  • 1
3

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

drac_o
  • 427
  • 5
  • 11
2

@Ashika's answer works fantastically if you want (0,0) to be represented in the top, left corner, per standard matrix convention. If however you would prefer to put (0,0) in the lower left hand corner, in the style of the standard coordinate system, 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.

Max von Hippel
  • 2,856
  • 3
  • 29
  • 46
  • 1
    A normal mathematical convention is to have element (0,0) (or rather (1,1)) in the top left corner when we talk about matrices, which arrays represent. I guess you wanted to allude to the coordinate system, but the way you phrased it - mixes up different concepts and is simply untrue. – emperor-shallots Aug 23 '21 at 09:18
  • Hi @jojo ... I wrote this answer in 2016, 1 year into a BS in math. A BS and part of a PhD later, I agree with you. I'll edit the answer accordingly. :) Thanks! – Max von Hippel Aug 25 '21 at 03:46
2
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
Mark Gun
  • 21
  • 2
0

Try this,

for (char[] temp : box) {
    System.err.println(Arrays.toString(temp).replaceAll(",", " ").replaceAll("\\[|\\]", ""));
}
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
Nambi_0915
  • 1,091
  • 8
  • 21
0

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();
}
awgtek
  • 1,483
  • 16
  • 28
0
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

Dhruvadeep
  • 38
  • 9