Jagged array (Ragged array) in Java
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.Arrays; class Main { // Program to illustrate Jagged array in Java public static void main(String[] args) { // Declare a jagged array containing three elements int[][] arr = new int[3][]; // Initialize the elements arr[0] = new int[] { 1, 2, 3 }; arr[1] = new int[] { 4, 5, 6, 7 }; arr[2] = new int[] { 8, 9 }; // print the array elements for (int[] row: arr) { System.out.println(Arrays.toString(row)); } } } |
Output:
[1, 2, 3]
[4, 5, 6, 7]
[8, 9]
Following is the memory representation of the above 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
.
1 2 3 4 5 6 |
int[][] arr = new int[3][]; // this will initialize the array elements by 0 arr[0] = new int[1]; arr[1] = new int[2]; arr[2] = new int[3]; |
2. We can also initialize the array upon declaration like this:
1 2 3 4 5 6 |
int[][] arr = new int[][] { new int[] { 1, 2, 3 }; new int[] { 4, 5, 6, 7 }; new int[] { 8, 9 }; }; |
Alternatively, we can use the following shorthand form:
1 2 3 4 5 6 |
int[][] arr = { new int[] { 1, 2, 3 }; new int[] { 4, 5, 6, 7 }; new int[] { 8, 9 }; }; |
3. We can also omit the new operator from the element’s initialization:
1 2 3 4 5 6 |
int[][] arr = { { 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9 } }; |
That’s all about jagged array in Java.
Reference: Jagged arrays (C# Programming Guide) | Microsoft Docs
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)