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 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

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[]

Feedback about page:

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


Arrays:
* Arrays
* Multidimensional and Jagged Arrays

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap