Java Language Multidimensional and Jagged Arrays


Example

It is possible to define an array with more than one dimension. Instead of being accessed by providing a single index, a multidimensional array is accessed by specifying an index for each dimension.

The declaration of multidimensional array can be done by adding [] for each dimension to a regular array decleration. For instance, to make a 2-dimensional int array, add another set of brackets to the declaration, such as int[][]. This continues for 3-dimensional arrays (int[][][]) and so forth.


To define a 2-dimensional array with three rows and three columns:

int rows = 3;
int columns = 3;
int[][] table = new int[rows][columns];

The array can be indexed and assign values to it with this construct. Note that the unassigned values are the default values for the type of an array, in this case 0 for int.

table[0][0] = 0;
table[0][1] = 1;
table[0][2] = 2;

It is also possible to instantiate a dimension at a time, and even make non-rectangular arrays. These are more commonly referred to as jagged arrays.

int[][] nonRect = new int[4][];

It is important to note that although it is possible to define any dimension of jagged array, it's preceding level must be defined.

// valid
String[][] employeeGraph = new String[30][];

// invalid
int[][] unshapenMatrix = new int[][10];

// also invalid
int[][][] misshapenGrid = new int[100][][10];

How Multidimensional Arrays are represented in Java

Representation of multidimensional array at java

Image source: http://math.hws.edu/eck/cs124/javanotes3/c8/s5.html


Jagged array literal intialization

Multidimensional arrays and jagged arrays can also be initialized with a literal expression. The following declares and populates a 2x3 int array:

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

Note: Jagged subarrays may also be null. For instance, the following code declares and populates a two dimensional int array whose first subarray is null, second subarray is of zero length, third subarray is of one length and the last subarray is a two length array:

int[][] table = {
    null,
    {},
    {1},
    {1,2}
};

For multidimensional array it is possible to extract arrays of lower-level dimension by their indices:

int[][][] arr = new int[3][3][3];
int[][] arr1 = arr[0]; // get first 3x3-dimensional array from arr
int[] arr2 = arr1[0]; // get first 3-dimensional array from arr1
int[] arr3 = arr[0]; // error: cannot convert from int[][] to int[]