Java | Multidimensional Arrays

05 min read

Multi-Dimensional Arrays:

Implemented as array of arrays.

For example, a 2-D is treated as an array of several 1-D arrays. A 3-D array is treated as an array of several 2-D arrays.

If a 2-D array with 3 rows and 4 columns has to be created, Java does this by creating 3 1-D arrays each with 4 elements in it. 

Java creates 3 rows with 4 elements each, using the new operator. The starting address of each row, thus created, would be returned by the 'new' operator. So, totally 3 addresses would be returned. Therefore, an array of 3 reference variables is needed to hold these 3 addresses. And to access all the rows and columns through this array of reference variables, first of all, the starting address of this array is needed. So, the starting address of this reference array has to be stored in a variable (reference of reference variable).

int[ ] [ ] a

This is what happens internally whenever a 2-D array is created.

Creates a 2-ID array with,

  • int[ ] [ ] a = new int[3][4];  ->  3 rows and 4 columns
  • float[ ][ ] f = new float[3][3];  ->  3 rows and 3 columns
  • int[ ][ ] a= {{1, 2, 3},{4, 5, 6},{7, 8, 9} };

The 2-D array 'a' is created with 3 rows and 3 columns.

Row '0' elements — 1, 2, 3 Row 'I' — 4, 5, 6 Row '2' — 7, 8, 9

 

Multi-dimensional arrays are of 2 types as follows:

  • Regular Arrays
  • For an N-dimensional array, all (N-1) dimensional arrays are of the same length. Eg: int[] [] a
  •  Ragged Arrays (or) Jagged array. But 'Jagged array' is the term used commonly in languages like C#. They are of varying length.
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error