Java – Best way to print 2D array?

Java – Best way to print 2D array?

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

I would prefer generally foreach when I dont need making arithmetic operations with their indices.

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

Java – Best way to print 2D array?

Simple and clean way to print a 2D array.

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

Leave a Reply

Your email address will not be published.