April 1, 2011

Multi-dimensional Arrays in Java

Multi-dimensional arrays are actually arrays of arrays. For example, a 2-dimensional array of type String is really an object that refers to an array, each element of which is referring to another String array.

The second dimension actually refers to the actual String objects.

Example of a 2-dimensional array:

public class Test {
     
   public static void main(String args[]) {
         
      String[][] strArr2d = new String[3][];

      strArr2d[0] = new String[2];
      strArr2d[1] = new String[3];
      strArr2d[2] = new String[4];

      strArr2d[0][0] = "Hello";
      strArr2d[0][1] = "World";

      strArr2d[1][0] = "Thou";
      strArr2d[1][1] = "Art";
      strArr2d[1][2] = "That";

      strArr2d[2][0] = "Truth";
      strArr2d[2][1] = "Shall";
      strArr2d[2][2] = "Always";
      strArr2d[2][3] = "Prevail";
   }
}

Example of a 3-dimensional array:


public class Test {
     
   public static void main(String args[]) {
         
      int[][][] strArr3d = new int[2][][];

      strArr3d[0] = new int[2][];
      strArr3d[1] = new int[2][];

      strArr3d[0][0] = new int[2];
      strArr3d[0][1] = new int[2];
         
      strArr3d[1][0] = new int[2];
      strArr3d[1][1] = new int[2];

      strArr3d[0][0][0] = 1;
      strArr3d[0][0][1] = 2;

      strArr3d[0][1][0] = 3;
      strArr3d[0][1][1] = 4;

      strArr3d[1][0][0] = 5;
      strArr3d[1][0][1] = 6;

      strArr3d[1][1][0] = 7;
      strArr3d[1][1][1] = 8;
   }
}

No comments:

Post a Comment