Jagged Array In Java

In Java, a jagged array comprises arrays that can have different numbers of elements, unlike a two-dimensional array where all rows and columns must have equal lengths.

Ragged arrays, also referred to as irregular arrays, are arrays created with varying sizes for each array in the declaration. For instance, a jagged array consisting of three rows may have the initial row containing three elements, the second row containing two elements, and the third row containing four elements.

Example of Jagged Array

A jagged array consisting of three rows can be structured such that the first row contains three elements, the second row contains two elements, and the third row contains four elements.

Example

int[][] jaggedArray = {

    {1, 2, 3},

    {4, 5},

    {6, 7, 8, 9}

};

Declaration and Initialization of Jagged Array

In Java, it is possible to declare and initialize a jagged array by using this syntax:

Syntax:

Example

datatype[][] arrayName = new datatype[numRows][];

arrayName[0] = new datatype[numColumns1];

arrayName[1] = new datatype[numColumns2];

...

arrayName[numRows-1] = new datatype[numColumnsN];

In this context, the datatype signifies the type of data that the array elements hold, numRows indicates the total row count within the jagged array, and numColumns1, numColumns2, ..., numColumnsN represent the individual column counts for each respective row. It is important to note that the column count in each row can vary.

The initial line generates a multidimensional array comprising numRows rows, where each row is automatically set to null.

The following code segments are responsible for setting up each row in the jagged array. A new single-dimensional array is generated with a size of numColumns for every row, and it is then linked to the respective row in the jagged array.

Ways to Initialize a Jagged Array

Apart from the conventional method of declaring and setting up a jagged array, as demonstrated in the previous response, there are various alternative techniques available for initializing a jagged array in Java.

1. Using Array Literals

One way to initialize jagged array elements directly is by using array literals.

Example

int[][] jaggedArray = { {1, 2}, {3, 4, 5}, {6, 7, 8, 9} };

In this example, a jagged array is being initialized with three rows of varying lengths. The first row contains two elements, the second row contains three elements, and the third row contains four elements.

Example

Example

public class Main {  

    public static void main(String[] args) {  

        // create a jagged array with three rows  

        int[][] jaggedArray = {  

            {1, 2, 3},   // first row has three columns  

            {4, 5},      // second row has two columns  

            {6, 7, 8, 9}   };  // third row has four columns  

        // loop through each row of the jagged array  

        for (int i = 0; i < jaggedArray.length; i++) {  

            // loop through each column of the current row  

            for (int j = 0; j < jaggedArray[i].length; j++) {  

                // print the value at the current position in the array  

                System.out.print(jaggedArray[i][j] + " ");  

            }  

            // move to the next line for the next row  

            System.out.println();  

        }  

    }  

}

Output:

Output

1 2 3

4 5

6 7 8 9

2. Using Nested Loops

Nested loops can also be employed for setting up the elements of a jagged array when the elements need to be generated through code. This method can offer advantages in such scenarios.

Example

int[][] jaggedArray = new int[3][];

for (int i = 0; i < jaggedArray.length; i++) {

    jaggedArray[i] = new int[i + 1];

    for (int j = 0; j < jaggedArray[i].length; j++) {

        jaggedArray[i][j] = i + j;

    }

}

In this example, we create a jagged array with a total of three rows. The first row contains one element, the second row contains two elements, and the third row contains three elements. By utilizing nested loops and a straightforward formula, we populate the elements within the jagged array.

Example

Example

public class Main {  

    public static void main(String[] args) {  

        // Create a 2-D jagged array with 4 rows  

        int[][] jaggedArray = new int[4][];  

        // Set the number of columns for each row  

        jaggedArray[0] = new int[1];  

        jaggedArray[1] = new int[2];  

        jaggedArray[2] = new int[3];  

        jaggedArray[3] = new int[4];  

        // Fill the array with values starting from 1  

        int value = 1;  

        for (int i = 0; i < jaggedArray.length; i++) {  

            for (int j = 0; j < jaggedArray[i].length; j++) {  

                jaggedArray[i][j] = value;  

                value++;  

            }  

        }  

        // Print the values in the array  

        for (int i = 0; i < jaggedArray.length; i++) {  

            for (int j = 0; j < jaggedArray[i].length; j++) {  

                System.out.print(jaggedArray[i][j] + " ");  

            }  

            System.out.println();  

        }  

    }  

}

Output:

Output

1

2 3

4 5 6

7 8 9 10

3. Using Java 8 Streams

By utilizing Java 8 streams, it is possible to efficiently generate and set up a jagged array in one line by employing the Arrays.stream method followed by the toArray method as demonstrated below:

Example

int[][] jaggedArray = Stream.of(

        new int[]{1, 2},

        new int[]{3, 4, 5},

        new int[]{6, 7, 8, 9})

        .toArray(int[][]::new);

In this example, we are creating a jagged array with three rows. The first row contains two elements, the second row contains three elements, and the third row contains four elements. By using the Arrays.stream method, we convert each one-dimensional array into a stream of integers. Subsequently, the toArray method gathers these streams to form the jagged array.

Example

Example

import java.util.*;  

public class Main {  

    public static void main(String[] args) {         

        // create a jagged array with three rows  

        int[][] jaggedArray = {  

            {1, 2, 3},   // first row has three columns  

            {4, 5},      // second row has two columns  

            {6, 7, 8, 9} // third row has four columns  

        };  

        // loop through each row of the jagged array using streams  

        Arrays.stream(jaggedArray)  

            .forEach(row -> {  

                // loop through each element of the current row using streams  

                Arrays.stream(row)  

                    .forEach(element -> System.out.print(element + " "));  

                // move to the next line for the next row  

                System.out.println();  

            });  

    }  

}

Output:

Output

1 2 3

4 5

6 7 8 9

4. Dynamic Jagged Array

In Java, a dynamic jagged array can be formed by composing an array that contains arrays. Each individual array within this structure signifies a row within the two-dimensional array. Subsequently, memory can be assigned to each sub-array to define its column count.

Example

Example

import java.util.Scanner;  

public class Main {  

public static void main(String[] args) {  

// Create a Scanner object to get user input  

Scanner scanner = new Scanner(System.in);  

    // Prompt the user to enter the number of sub-arrays  

    System.out.print("Enter the number of sub-arrays: ");  

    int numberOfArrays = scanner.nextInt();  

    // Declare the jagged array with the number of sub-arrays  

    int[][] jaggedArray = new int[numberOfArrays][];  

    //Loop through each sub-array to allocate memory and get user input for each element  

    for (int i = 0; i < numberOfArrays; i++) {  

        // Prompt the user to enter the size of the current sub-array  

        System.out.print("Enter the size of sub-array " + (i + 1) + ": ");  

        int sizeOfSubArray = scanner.nextInt();  

        // Allocate memory to the current sub-array  

        jaggedArray[i] = new int[sizeOfSubArray];  

        //Loop through each element of the current sub-array to get user input  

        for (int j = 0; j < sizeOfSubArray; j++) {  

            System.out.print("Enter the element at index " + j + " of sub-array " + (i + 1) + ": ");  

            jaggedArray[i][j] = scanner.nextInt();  

        }  

    }  

    // Print the jagged array  

    System.out.println("The jagged array is:");  

    for (int i = 0; i < numberOfArrays; i++) {  

        for (int j = 0; j < jaggedArray[i].length; j++) {  

            System.out.print(jaggedArray[i][j] + " ");  

        }  

        System.out.println();  

    }  

    // Close the scanner object  

    scanner.close();  

}  

}

Output:

Output

Enter the number of sub-arrays: 3

Enter the size of sub-array 1: 2

Enter the element at index 0 of sub-array 1: 1

Enter the element at index 1 of sub-array 1: 2

Enter the size of sub-array 2: 3

Enter the element at index 0 of sub-array 2: 3

Enter the element at index 1 of sub-array 2: 4

Enter the element at index 2 of sub-array 2: 5

Enter the size of sub-array 3: 1

Enter the element at index 0 of sub-array 3: 6

The jagged array is:

1 2

3 4 5

6

Advantages of Jagged Array

Jagged arrays have several advantages over multidimensional arrays with a fixed size:

  • Memory Efficiency: Jagged arrays are more memory-efficient than multidimensional arrays because they only allocate memory for the elements they need. In a multidimensional array with a fixed size, all the memory is allocated, even if some elements are unused.
  • Flexibility: Jagged arrays are more flexible than multidimensional arrays because they can have different sizes for each row. Jagged arrays enable the representation of non-rectangular or irregular data structures.
  • Easy to Initialize: Jagged arrays are easy to initialize because you can specify the size of each row individually. The suitability of jagged arrays lies in their ability to store data that varies in size or is generated dynamically.
  • Enhanced Performance: Jagged arrays can provide enhanced performance in certain scenarios, such as when you need to perform operations on each row independently or when you need to add or remove rows dynamically.
  • More natural representation of data: In some cases, jagged arrays may be a more natural representation of data than rectangular arrays. For example, when working with irregularly shaped data such as geographic maps, a jagged array can be a more intuitive way to represent the data.
  • Easier to manipulate: Jagged arrays can be easier to manipulate than rectangular arrays because they allow for more direct access to individual elements. With rectangular arrays, you may need to use more complex indexing or slicing operations to access subsets of the data.
  • How do jagged arrays differ from multi-dimensional arrays?

A jagged array differs from a multi-dimensional array. The distinctions between jagged arrays and multi-dimensional arrays are outlined in the table below.

Aspect Jagged Array Multi-dimensional Array
Structure Each row (or sub-array) can have a different length. All rows must have the same number of columns.
Memory Allocation Memory is allocated separately for each sub-array, making it more memory-efficient when varying row sizes are needed. It allocates a continuous block of memory for all elements, potentially wasting memory when row lengths vary.
Declaration int[][] jaggedArray = {{1, 2, 3},{4, 5},{6, 7, 8, 9}}; int[][] multiArray = new int[3][3]; // Fixed size: 3 rows, 3 columns
Accessing Elements Jagged Array: jaggedArray[row][column] Multi-dimensional Array: multiArray[row][column]
Uses Cases It is useful when dealing with irregular data structures like variable-length rows in tables. It is ideal for grids, matrices, or fixed-size tables.

Jagged Array MCQs

  1. What is a jagged array in Java?
  • A multi-dimensional array with an equal number of columns in each row
  • A one-dimensional array of integers
  • An array of arrays where each sub-array can have a different length
  • An array where memory is pre-allocated for all elements

A jagged array is a type of array in programming that consists of arrays within an array, where each inner array can have a varying number of elements. This results in a structure where rows may contain different quantities of columns.

What will be displayed as the result when the provided code is executed?

Example

int[][] jagged = {

    {1, 2, 3},

    {4, 5},

    {6}

};

System.out.println(jagged[1][1]);

Explanation: jagged1 refers to the second row and the second element, which is 5.

  1. Which of the following correctly declares a jagged array with 3 rows in Java?
  • int jagged = new int[3];
  • int jagged = new int3;
  • int jagged = new int3;
  • int jagged = new int3;

Explanation: In Java, to create a jagged array, we define the number of rows first. The column sizes can be specified later individually.

  1. Which statement about jagged arrays is true?
  • All rows must have the same number of columns
  • Each sub-array can have a different length
  • Java does not support jagged arrays
  • Jagged arrays must be square

Jagged arrays are arrays where each row can have a different number of columns, allowing them to store non-uniform data effectively.

  1. What result will the following code produce?
  2. Example
    
    int[][] jagged = new int[2][];
    
    jagged[0] = new int[]{1, 2};
    
    jagged[1] = new int[]{3, 4, 5};
    
    System.out.println(jagged[1].length);
    
  • Compilation error

Illustration: In the jagged array, denoted as jagged[1], there are a total of 3 elements. Hence, the length of jagged[1] is 3.

Input Required

This code uses input(). Please provide values below: