Jagged Array (Ragged Array) in Java

In this post, we will see how to declare and initialize jagged array in Java.


 

A jagged array, also known as ragged array or “array of arrays”, is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes unlike C-styled arrays that are always rectangular.

 
We know that a two dimensional array is nothing but an array of single-dimensional arrays. Therefore, it is possible to create a two dimensional array in Java where individual one dimensional arrays has different length.

To illustrate, consider below example which declares a single-dimensional array having three elements, each of which is a single-dimensional array of integers. The first element is an array of 3 integers, the second is an array of 4 integers, and the third is an array of 2 integers. It uses initializers to fill the array elements with values.

 

Download   Run Code

Output:

[1, 2, 3]
[4, 5, 6, 7]
[8, 9]

 
Below is memory representation of above Jagged array.

Jagged Array

 
1. If we don’t specify an array initializer, the default value is assigned to each element of the array depending upon the type of array. 0 is default value for int or long or short or byte, null is default value for String and 0.0 is the default value for double or float.

 
2. We can also initialize the array upon declaration like this:

or we can use the following shorthand form.

 
3. We can also omit the new operator from the elements initialization:

 
 
References: Jagged Arrays (C# Programming Guide) | Microsoft Docs

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz