Jagged Array in Java with Program Example

In this java programming tutorial post, we will understand the working of jagged array in java. For understanding this concept, it is necessary that you understand the working of Arrays in Java and Multi-dimensional arrays in java.

Jagged array in java is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays. Lets see a Program example of 2-D jagged array and then we will try to understand the program.

2-D Jagged Array in Java Example Program
// Program to demonstrate 2-D jagged array in Java
class Main
{
    public static void main(String[] args)
    {
        // Declaring 2-D array with 2 rows
        int arr[][] = new int[2][];
 
        // Making the above array Jagged
 
        // First row has 3 columns
        arr[0] = new int[3];
 
        // Second row has 2 columns
        arr[1] = new int[2];
 
        // Initializing array
        int count = 0;
        for (int i=0; i<arr.length; i++)
            for(int j=0; j<arr[i].length; j++)
                arr[i][j] = count++;
 
        // Displaying the values of 2D Jagged array
        System.out.println("Contents of 2D Jagged Array");
        for (int i=0; i<arr.length; i++)
        {
            for (int j=0; j<arr[i].length; j++)
                System.out.print(arr[i][j] + " ");
            System.out.println();
        }
    }
}
Output
Contents of 2D Jagged Array
0 1 2
3 4
Program Explanation –

As you can see in the above example we have created a 2-D jagged array. At the first line where we declared the 2D array, we only assigned the number of rows i.e. 2. However, we kept the column value blank as we will have different column value for individual rows. Now for the first row, we set the column value as 3 which means the first row will hold 3 values. Now for the second row, we declare the column size of 2 so it will hold only 2 values.  Thus this creates a asymmetric multi-dimensional jagged array. Here’s the visual representation of the same jagged array –

jagged array in java diagram

Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *