15

How to print multi-dimensional array using for-each loop in java? I tried, foreach works for normal array but not work in multi-dimensional array, how can I do that? My code is:

class Test
{
   public static void main(String[] args)
   {
      int[][] array1 = {{1, 2, 3, 4}, {5, 6, 7, 8}};
      for(int[] val: array1)
      {
        System.out.print(val);
      }
   } 
}
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214

4 Answers4

13

Your loop will print each of the sub-arrays, by printing their address. Given that inner array, use an inner loop:

for(int[] arr2: array1)
{
    for(int val: arr2)
        System.out.print(val);
}

Arrays don't have a String representation that would, e.g. print all the elements. You need to print them explicitly:

int oneD[] = new int[5];
oneD[0] = 7;
// ...

System.out.println(oneD);

The output is an address:

[I@148cc8c

However, the libs do supply the method deepToString for this purpose, so this may also suit your purposes:

System.out.println(Arrays.deepToString(array1));
pb2q
  • 58,613
  • 19
  • 146
  • 147
9

If you just want to print the data contained in the int array to a log, you can use

Arrays.deepToString

which does not use any for loops.

Working Code.

import java.util.*;
public class Main
{
   public static void main(String[] args)
   {
      int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}};
        System.out.println(Arrays.deepToString(array));
   } 
}

Output

[[1, 2, 3, 4], [5, 6, 7, 8]]
Ajay George
  • 11,759
  • 1
  • 40
  • 48
4

This is a very general approach that works in most languages. You will have to use nested loops. The outer loop accesses the rows of the array, while the inner loop accesses the elements within that row. Then, just print it out and start a new line for every row (or choose whatever format you want it to be printed in).

for (int[] arr : array1) {
  for (int v : arr) {
    System.out.print(" " + v);
  } 
  System.out.println();
}
brimborium
  • 9,362
  • 9
  • 48
  • 76
2

The current output would look something like:

[I@1e63e3d
...

which shows the string representation for an integer array.

You could use Arrays.toString to display the array content:

for (int[] val : array1) {
   System.out.println(Arrays.toString(val));
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276