Using 2D and 3D Arrays in Java

Creation and Use

We can create rectangular 1D, 2D, 3D, ... arrays in Java fairly straightforwardly. The code

   int[]     array1d = new int[30];
   int[][]   array2d = new int[9][14];
   int[][][] array3d = new int[2][7][19];
This defines

You can then read or write to these elements, e.g.,

  array2d[3][3] = array1d[0] + array3d[1][0][18]; 
    // not array2d[3,3] = ... !!

You can also get “slices” of a multidimensional array. For example, array2d above is actually an array of 9 arrays (array2d[0] through array2d[8]), each of which has length 14.

Printing

If you import java.util.Arrays, you can convert a one-dimensional array to a nice string representation via Arrays.toString(...).

For two-dimensional arrays, you could use the following code to convert it to a printable string.

public static String toStr( int[][] A) {
     String s = "";
     for (int row=0; row < A.length ; ++row) {
       s += Arrays.toString(A[row]) + "\n";
     }
     return s;

For 3D arrays, you could either use nested loops, or just print one 2D slice of the array at a time, e.g.,

   System.out.println(toStr(array3d[0]));
   System.out.println(toStr(array3d[1]));

Warning: code like

int[] array2d;

array2d[0][0] = 42;
won't work, because array2d will start out as null, rather than being an actual array object.