Multidimensional Arrays in Java

In Java, you can make arrays upto any dimension. A one-dimensional array is like a linear chain. You can have arrays of higher dimension like :

  • Two dimensional array :– An array of one dimensional arrays i.e. an array whose every element is a one dimensional array. A two dimensional array is also called a matrix.
  • Three dimensional array :- An array of two dimensional arrays i.e. an array whose every element is a two dimensional array.
  • Four dimensional array :- An array of three dimensional arrays i.e. an array whose every element is a three dimensional array.
  • An so on

1. Two Dimensional Arrays in Java

The syntax to declare a two dimensional array in Java is :


1.1 Example

Example below computes the table of numbers from 1 to 9:

Output :

 


1.2 Graphical representation of a Two-dimensional array

Graphically the 2D array(Matrix) can be visualized as:

Numbers[9][10], a 9x10 matrix
Numbers[9][10], a 9×10 matrix

2. Three Dimensional Arrays in Java

The Syntax to declare a three dimensional array in Java is:

 


2.1 Example

Output :

 


2.2 Graphical representation of a Three-dimensional array

Graphically the three dimensional array can be visualized as:

Three Dimensional array
Visualisation of three Dimensional array of dimensions 3,4,5.


3. Four and higher dimensional arrays

You can make an array of any dimension you want. To make an array of 4-dimensions the syntax would be:

  • That is you have to place as many brackets as the dimension of the array is.
  • Dimensions are in order i.e first pair of brackets represents first dimension and last pair of brackets represents the last dimension.

 


4. Miscellaneous Topics

4.1 The last dimension of an array can be assigned separately

You can leave the last dimension blank i.e for the 4D array this is valid :

The last dimension would be assigned separately, like:

 


Lets have a concrete example for a 3D array.

Output :

 


4.2 Jagged Array

Since a two dimensional array is an array of arrays. You can have a 2D array whose column length is variable. Such an array is called a jagged array.

Note: A Jagged array is a special case of the last section i.e when you assign the last dimension separately. It generally refers to a variable column two dimensional array.

Output :