![]() |
VOOZH | about |
In Java, a Jagged array is a multidimensional array where each row can have a different number of columns. When we work with a jagged array, one thing to keep in mind is that the inner array can be of different lengths. It is like a 2D array, but each row can have a different number of elements.
0 1 2 3 4
The image below demonstrates a Jagged array, where each row in a 2D array can have a different number of elements.
The declaration of Jagged array is:
data_type array_name[][] = new data_type[n][]; // n= no. of rows
array_name[0] = new data_type[n1] //n1= no. of columns in row-1
array_name[1] = new data_type[n2] //n2= no. of columns in row-2
array_name[2] = new data_type[n3] //n3= no. of columns in row-3
.
.
.
and so on
The Alternative ways to initialize a Jagged array is listed below:
// Method 1
int arr_name[][] = new int[][] {
new int[] {10, 20, 30 ,40},
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};// Method 2
int[][] arr_name = {
new int[] {10, 20, 30 ,40},
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};// Method 3
int[][] arr_name = {
{10, 20, 30 ,40},
{50, 60, 70, 80, 90, 100},
{110, 120}
};
Example 1: Here row i has i + 1 columns.
Contents of 2D Jagged Array 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Explanation: In the above example, we are creating a jagged array where each row will get one more element than the previous one, suppose the first row has one element then the second row has two element and then the third row has three element and so on. It fills the array with numbers starting from 0 and then prints them
Example 2: User Input Jagged Array
Enter the number of sub-arrays: 4
Enter the size of sub-array 1: 3
Enter the size of sub-array 2: 4
Enter the size of sub-array 3: 2
Enter the size of sub-array 4: 4Enter the elements of sub-array 1:
1 2 3Enter the elements of sub-array 2:
5 6 7 8Enter the elements of sub-array 3:
6 7Enter the elements of sub-array 4:
1 2 3 4
The jagged array is:
1 2 3
5 6 7 8
6 7
1 2 3 4
The advantages of using a jagged array is listed below:
Note: Jagged arrays can make the code a bit harder to write and read, so itβs best to use them only when really needed.