This post will discuss how to declare and initialize a jagged array in Java.

A jagged array, also known as a 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 have different lengths.

To illustrate, consider the following example, which declares a single-dimensional array having three elements, each of which is a single-dimensional integer array. 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]

 
Following is the memory representation of the above Jagged array.

Jagged Array

 
1. If we don’t specify an array initializer, the default value is assigned to each array element depending upon the type of array. 0 is the default value for int or long or short or byte, null is the 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:

Alternatively, we can use the following shorthand form:

 
3. We can also omit the new operator from the element’s initialization:

That’s all about jagged array in Java.

 
Reference: Jagged arrays (C# Programming Guide) | Microsoft Docs