Jagged Arrays in Java

Java implements an N dimensional array as an array of other N-1 dimensional arrays. The size of these N-1 dimensional arrays can be same or different for different N-1 dimensional arrays. If they are different, they are called jagged array.

For Example : 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 of two dimensions.

All the discussions below concern jagged arrays of two dimensions as they are easy to visualize.


1. Simultaneous declaration and initialization.

You can simultaneously declare and initialize the data members of a jagged array using curly braces like:

1.1 Example :

Output :

 


2. Separate memory allocation for second dimension

You can declare the array first and then initialize the 2nd dimension separately like :

Or you can declare the array, allocate the memory for them, but do not initialize them, like:

It may be needed in situations where you don’t have the data at the start, as you progress you get the data and fill them in; like initializing the array by taking user input.

2.1 Example :

Output :

 


3. Graphical Representation of a Jagged Array

The example array can be graphically visualized as :

A jagged array of two dimensions.
A jagged array of two dimensions.

 


4. Conclusion

You may have realized by now that the jagged arrays are quite versatile and memory efficient.