An element of a 2d array is a 1d array. If you define an array directly new int[5][4]
then length of each row is 4
, otherwise it may vary. When you create a 2d array with undefined row length, each element of it, actually 1d array, is not initialized yet and is null
. When you create 1d array of int[]
it is initialized with zeros by default. If you define 2d array directly the elements of its rows are initialized with zeros.
Initialization of 2d array
You can define column length without row length:
int[][] arr = new int[5][];
arr[0] = new int[]{1, 2, 3};
arr[3] = new int[2];
arr[3][1] = 9;
arr[4] = new int[]{3, 3, 2, 1, 6, 7};
// output:
[1, 2, 3]
null
null
[0, 9]
[3, 3, 2, 1, 6, 7]
You can define column and row length:
int[][] arr2 = new int[3][3];
arr2[0][0] = 1;
// output:
[1, 0, 0]
[0, 0, 0]
[0, 0, 0]
You can define each element of the 2d array at creation time, optionally with reserved rows for further operations:
int[][] arr3 = new int[][]{{1, 2, 3}, {4, 5}, {6}, null};
// output:
[1, 2, 3]
[4, 5]
[6]
null