Java - Multi-Dimensional Arrays Initializing


You may initialize a multi-dimensional array by supplying the list of values.

The number of initial values for each dimension will determine the length of each dimension.

The list of values for a level is enclosed in braces.

For a two-dimensional array, the list of values for each row is enclosed in a pair of braces:

int[][] arr = {{10, 20, 30}, {11, 22}, {222, 333, 444, 555}};

The code above creates a two-dimensional array with three rows.

  • The first row contains three columns with values 10, 20, and 30.
  • The second row contains two columns with values 11 and 22.
  • The third row contains four columns with values 222, 333, 444, and 555.

A zero-row and zero-column two-dimensional array can be created as shown:

int[][] empty2D = { };

Initialization of a multi-dimensional array of reference type.

String[][] acronymList = {{"JMF", "Java Media Framework"},
                          {"JSP", "Java Server Pages"},
                          {"Json", "Javascript data format"},
                          {"JMS", "Java Message Service"}};

You can initialize the elements of a multi-dimensional array at the time you create it.

int[][] arr = new int[][]{{1, 2}, {3,4,5}};