Multidimensional and Jagged Arrays

suggest change

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 a multidimensional array can be done by adding [] for each dimension to a regular array declaration. 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 assigned values 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 a jagged array, its 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

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


Jagged array literal initialization

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, whose second subarray has length zero, whose third has length one, and whose last has length two:

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

For a multidimensional array, it is possible to extract arrays of lower rank by their indices:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents