It allows you to delay decision regarding the number of columns, as well as define a different number of columns for different rows.
For example:
int [][] arr = new int[2][];
arr[0] = new int[5];
arr[1] = new int[3];
The first row of the array has 5 columns, but the second row has only 3 columns.
This is not possible if you specify the number of columns when you declare the 2D array.
It may become less confusing is you think of a multi-dimensional array as a 1 dimensional array whose elements are themselves arrays of a lower dimension.
So a 2 dimensional int array (int[][]
) is a 1 dimensional array whose elements are int
arrays (int[]
).
You can instantiate this array by specifying the number of elements:
int[][] arr = new int[2][];
which gives you an array of two int[]
elements, where the 2
elements are initialized to null
.
This is similar to initializing an array of some reference type:
Object[] arr = new Object[2];
which gives you an array of two Object
elements, where the 2
elements are initialized to null
.
The new int[2][3]
instantiation is actually the special case - since it instantiates both the outer array (the one having 2 elements) and the inner arrays (each having 3 elements), which are the elements of the outer array.