Multidimensional Arrays in Java

Multidimensional arrays are arrays of arrays. For instance, a 2D array is an array of 1D arrays and a 3 D array is an array of 2 D arrays, where each of those 2D arrays is again an array of 1D arrays.

 

Multidimensional array declaration and initializations

Declaration without initialization

int mArray[][];  or

int mArray1[][][]; or

int [] mArray2[][];

 

Initializing by specifying sizes

We can initialize a multidimensional array the same way as a single dimensional array specifying the sizes for each dimensions. 

Below example declare and initialize a 2-D array with 2 rows and 3 columns. 

int matrix[][] = new int [2][3];

This will create a matrix (or 2-Dimensional array) with 2 rows and 3 columns as:

0 0 0
0 0 0

 

Initializing using short hand notation

You can also initialize a 2D array with custom constant values similar to a 1D array using an initializer statement.

int [] [] mArray = {{0, 1, 2,3}, {4, 5, 6,7}}; ​

Resulting array will be:

0 1 2 3

4 5 6 7

 

Ragged array declarations and assignment

A 2-D array is an array of 1-D arrays.

In memory, there will be a one-dimensional array and each element of this array references a one-dimensional array representing each row. Every row can have different number of columns i.e. different row lengths. Arrays of this type are called ragged arrays.

You can define a ragged array either using an initializer with different length contents for each rows or by creating a 2-D array specifying only the number of rows and then creating individual row arrays as below:

int matrix[][]= new int[2][]; // we are not specifying column size

matrix[0]= new int[3]; //column size for row 1 (index 0)

matrix[1]= new int[4]; //column size for row 2 (index 1)

Note that we gave only the number of rows in the initializer and then gave different column lengths for different rows separately. Above matrix will now look as:

0 0 0
0 0 0 0

 

Points to Remember

  1. Multidimensional arrays are arrays of arrays.

    • Verify using the getClass().isArray() methodSystem.out.print(arr[0].getClass().isArray()); will return true for a valid multi dimensional array. 

  2. Number of brackets in declaration (left side) correspond to the dimension.

    • We can have the brackets anywhere within the declaration, combine declaration and initialization etc.

  3. We use nested curly braces. Number of nestings denote the dimension: { } for ID, {{ }} for 2D. {{{ }}} for 3D etc. 

  4.  You can specify empty arrays or arrays with 0 size.

    • int[ ] i[ ] = { { 1, 2 }, { 3 }, { } } ;

  5. You can also initialize a sub array within a multidimentional array as null.

    • int[ ] i[ ] = { { 1, 2 }, { 3 }, null } ;

  6. You can declare a sub array of a multidimensional array using new keyword within a short hand initializer:

    • char cA[][] = { new char[ ]{ 'a', 'b', 'c' } , new char[ ]{   'a', 'b', 'c' } };

    • char cA[][] = { new char[ ]{ 'a', 'b', 'c' } , new char[3]};

  7. Even when you declare the sub arrays, you have to either specify size or use short hand:

    • char cA[][] = { new char[ ]{ 'a', 'b', 'c' } , new char[3]{   'a', 'b', 'c' } }; is NOT legal.

  8. Multidimensional arrays in Java are ragged arrays.

    1. Different rows can have different length.

    2. Length of each row can be found as aa[0].length, arr[1].length etc. 

 

Accessing elements of multidimensional array

Similar to single dimensional arrays, we can access values in a single dimensional array using indexes.

Consider below array:

0 1 2 3

4 5 6 7

We can access the elements of above array as:

mArray[0][0] will give 0.

mArray[0][1] will give 1.

mArray[0][2] will give 2.

mArray[1][0] will give 4.

mArray[1][1] will give 5.

and so on.

Similar to 1-D arrays, we will get an ArrayIndexOutOfBounds exception if we try to access a non-existent array location.

mArray[2][1] will give exception as there are only two rows and their indexes are 0 and 1.

mArray[0][4] will give exception as there are only four columns and their indexes are 0,1,2 and 3.

 

A 2-D array is an array of 1-D arrays. Try to guess the output for below:

System.out.print (mArray[0].length);

System.out.print (mArray[1].length);

System.out.print (mArray[1][2]);

Output will be

4

4

6

mArray[0] represent the first row array and hence mArray[0].length will be 4.

mArray[1] represent the second row array and hence mArray[1].length will be 4. In Java, different rows can be of different lengths.

mArray[1][2] is the third element in second row, which is 6. Note that array indexes in java are 0-based. 

 

Traversing a 2D array

We can make use of a nested for loop to traverse a 2-D array:

for(int i=0;i<ROWS;i++)

    {

      for(int j=0;j<COLS;j++)

      {

        System.out.print(" "+matrix[i][j]);

      }

      System.out.println();

 }

Similarly we can traverse a ragged array as:

for(int i=0;i<matrix.length;i++)

    {

      for(int j=0;j<matrix[i].length;j++)

      {

        System.out.print(" "+matrix[i][j]);

      }

      System.out.println();

 }

 

Though not very common, we can have arrays with more dimensions than 2. Consider an example of a 3D array initializer:

int [][][] arr3D = {{{1,2},{3,4}},{{1,2},{3,4}}};

Note the extra curly braces for a 3D array. There will be two level nesting of curly braces for a 3D array whereas 1 level of nesting for a 2D array ( e.g. {{0, 1}, {2, 3}, {4, 5}} ) and no nesting of braces for a 1D array (e.g. {1,2}). 

You can see that 3D arrays are arrays of arrays of arrays. You can also initialize them as:

int [][][] arr3D1 = new int [2][2][2];

int[] arr1D={1,2};

arr3D1[0][0]=arr1D;

arr3D1[0][1]=arr1D;

...

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!

Quick Notes Finder Tags

Activities (1) advance java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (52) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exceptions (4) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (4) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (4) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (4) Java Programmer 2 (2) Javascript Frameworks (1) Java SE Professional (1) JSP (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quizzes (17) references (2) resources (1) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Sorting (1) source code management (1) spring (4) spring boot (1) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)