4

I always get confused why does the 2D array in Java has a strict requirement for declaring the size of the row but not the column, this confuses further with 3D and 4D arrays.

// Invalid, 2D array with no row and no column?
int[][] arr = new int[][];
// Valid, 2D array of size 2X3
int[][] arr = new int[2][3];
// Valid, column size is not specified, size of 2D array?
int[][] arr = new int[2][];
// Valid, column size is not specified, size of 3D array?
int[][][] arr = new int[2][][];
Community
  • 1
  • 1
Shahid Sarwar
  • 1,209
  • 14
  • 29

2 Answers2

7

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

You can add curly brackets {} to the end. This is valid, an empty 2D array with no rows and no columns:

int[][] arr = new int[][]{};

See also:
Initializing a 2D array with only the number of rows
Array declaration and initialization in Java