Multidimensional Arrays in Java

A multidimensional array, is when each element of an array is also an array. Let's look at a simple 2D array.


public class MyClass {

  public static void main(String[] args) {

    int[][] myMultiArray = new int[2][3];

  }
}

Then you can assign values to each element like this.

public class MyClass {

  public static void main(String[] args) {

    int[][] myMultiArray = new int[2][3];

myMultiArray[0][0] = 1; myMultiArray[0][1] = 2; myMultiArray[0][2] = 3; myMultiArray[1][0] = 4; myMultiArray[1][1] = 5; myMultiArray[1][2] = 6; } }

Another shorter way to do it, is like this.

public class MyClass {

  public static void main(String[] args) {

    int[][] myMultiArray = new int[2][];

myMultiArray[0] = new int[] {1,2,3}; myMultiArray[1] = new int[] {4,5,6}; } }

An even shorter way, is like this.

public class MyClass {

  public static void main(String[] args) {

   int[][] myMultiArray = {
                                     {1,2,3},
                                     {4,5,6}
                                     };

  }
}

But what happens when you try to get the array's length?

public class MyClass {

  public static void main(String[] args) {

   int[][] myMultiArray = {
                                     {1,2,3},
                                     {4,5,6}
                                     };
    System.out.println(myMultiArray.length);
  }
}
2

Does that seem wrong? We do have six elements, right?

Actually not. The array called myMultiArray only has two elements. However, each of those elements is an array with three of their own elements. To get their lengths, you would do this.

public class MyClass {

  public static void main(String[] args) {

   int[][] myMultiArray = {
                                     {1,2,3},
                                     {4,5,6}
                                     };
    System.out.println(myMultiArray[0].length);
    System.out.println(myMultiArray[1].length);
  }
}

To print all the elements of the multidimensional array, will require you to nest a for loop inside another for loop. Like this.

public class MyClass {

  public static void main(String[] args) {

      int[][] myMultiArray = {
                             {1,2,3},
                             {4,5,6}
                             };

   for(int i = 0; i < myMultiArray.length; i++) {
     for(int j = 0; j < myMultiArray[i].length; j++) {
       System.out.print(myMultiArray[i][j] + " ");
     }
     System.out.println();
   }

  }
}

You can have as many dimensions as you want, and they do not have to be evenly sized. This creates what is called a "jagged" array.

public class MyClass {

  public static void main(String[] args) {

       int[][][][] myMultiArray = new int[2][3][6][4];


  }
}

Just keep in mind, with each added dimension, the multidimensional array gets more complex and challenging to work with.

Next Topic: Strings

Comments

Popular Posts