Jagged Array in Java

Jagged Array is a type of array in Java that can have different sizes of sub-arrays within it. This means that we can create a 2-dimensional array where each row has a variable number of columns. Jagged arrays can also be referred to as "ragged arrays".

To declare and initialize a jagged array, we use the following syntax:

less
data_type array_name[][] = new data_type[n][]; // n represents the number of rows array_name[] = new data_type[n1]; // n1 represents the number of columns in row-1 array_name[] = new data_type[n2]; // n2 represents the number of columns in row-2 . . . array_name[] = new data_type[nk]; // nk represents the number of columns in row-n

Alternatively, we can initialize a jagged array using the following methods:

java
int arr_name[][] = new int[][] { new int[] {10, 20, 30 ,40}, new int[] {50, 60, 70, 80, 90, 100}, new int[] {110, 120} };
java
int[][] arr_name = { new int[] {10, 20, 30 ,40}, new int[] {50, 60, 70, 80, 90, 100}, new int[] {110, 120} };
java
int[][] arr_name = { {10, 20, 30 ,40}, {50, 60, 70, 80, 90, 100}, {110, 120} };

To better understand how to use jagged arrays, we can look at some Java programs that demonstrate their use.

The first program creates a jagged array with two rows, where the first row has 3 columns and the second row has 2 columns. The array is then initialized with values and printed to the console.

The second program creates a jagged array with five rows, where the first row has 1 element, the second row has 2 elements, and so on. The array is then initialized with values and printed to the console.

Overall, jagged arrays are useful in situations where we need to store data in a table-like structure but the number of columns can vary across different rows.

Previous Post Next Post