Jagged Array

Jagged Array in Java

A jagged array in Java is a type of multidimensional array where each row can have a different number of columns. Unlike a regular 2D array where all rows must have the same number of columns, a jagged array allows for flexibility, making it useful for representing data structures like triangular matrices, irregular tables, and more.

This tutorial will explain what jagged arrays are, how to create and use them, and provide practical examples to help you understand their usage.


1. What is a Jagged Array?

A jagged array, also known as a "ragged" or "irregular" array, is a multidimensional array where the rows can have different lengths. In Java, a jagged array is essentially an array of arrays, where each inner array can have a different size.

Syntax for Declaring a Jagged Array:

dataType[][] arrayName;
  • dataType: The type of data that the array will hold (e.g., int, float, char).

  • arrayName: The name of the array variable.

Example:

int[][] jaggedArray;

This declares a jagged array of integers named jaggedArray.


2. Initializing a Jagged Array

After declaring a jagged array, you can initialize it by specifying the number of rows and then individually setting the size of each row.

Syntax for Initializing a Jagged Array:

arrayName = new dataType[numberOfRows][];
arrayName[rowIndex] = new dataType[numberOfColumns];

Example:

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

// Initialize each row with a different number of columns
jaggedArray[0] = new int[2]; // 2 columns in the first row
jaggedArray[1] = new int[3]; // 3 columns in the second row
jaggedArray[2] = new int[4]; // 4 columns in the third row

This creates a jagged array with 3 rows, where the first row has 2 columns, the second row has 3 columns, and the third row has 4 columns.

You can also initialize the jagged array with values directly:

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

3. Accessing Elements in a Jagged Array

Elements in a jagged array are accessed using their row and column indices, just like in a regular 2D array. However, since the rows can have different lengths, you must ensure that you are accessing a valid column index for the specific row.

Syntax for Accessing an Element:

arrayName[rowIndex][columnIndex]

Example:

int value = jaggedArray[1][2]; // Access the element at row 1, column 2
System.out.println("Value: " + value); // Output: 5

You can also update the value of an element in a jagged array:

jaggedArray[2][3] = 10; // Change the element at row 2, column 3 to 10

4. Iterating Over a Jagged Array

You can use nested loops to iterate over the elements of a jagged array. The outer loop iterates over the rows, and the inner loop iterates over the columns within each row.

Example using nested for loops:

for (int i = 0; i < jaggedArray.length; i++) {
    for (int j = 0; j < jaggedArray[i].length; j++) {
        System.out.println("Element at [" + i + "][" + j + "]: " + jaggedArray[i][j]);
    }
}

Example using an enhanced for loop (for-each loop):

for (int[] row : jaggedArray) {
    for (int value : row) {
        System.out.print(value + " ");
    }
    System.out.println();
}

5. Practical Examples

5.1 Example: Storing and Displaying Student Marks

Let's write a program that stores the marks of students in different subjects using a jagged array and displays them.

Example:

public class StudentMarks {
    public static void main(String[] args) {
        // Declare and initialize the jagged array
        int[][] studentMarks = {
            {85, 90},        // Student 1 has marks in 2 subjects
            {78, 88, 92},    // Student 2 has marks in 3 subjects
            {80, 75, 85, 90} // Student 3 has marks in 4 subjects
        };
        
        // Print the marks of each student
        for (int i = 0; i < studentMarks.length; i++) {
            System.out.print("Student " + (i + 1) + " marks: ");
            for (int j = 0; j < studentMarks[i].length; j++) {
                System.out.print(studentMarks[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output:

Student 1 marks: 85 90 
Student 2 marks: 78 88 92 
Student 3 marks: 80 75 85 90 

5.2 Example: Triangular Matrix Representation

A jagged array can be used to represent a triangular matrix, where each row has one more element than the previous row.

Example:

public class TriangularMatrix {
    public static void main(String[] args) {
        int[][] triangularMatrix = new int[5][];
        
        // Initialize the jagged array to represent a triangular matrix
        for (int i = 0; i < triangularMatrix.length; i++) {
            triangularMatrix[i] = new int[i + 1];
        }
        
        // Fill the matrix with values and print it
        int value = 1;
        for (int i = 0; i < triangularMatrix.length; i++) {
            for (int j = 0; j < triangularMatrix[i].length; j++) {
                triangularMatrix[i][j] = value++;
                System.out.print(triangularMatrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output:

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 

6. Advantages of Jagged Arrays

  • Memory Efficiency: Jagged arrays save memory by allowing different rows to have different lengths, avoiding the allocation of unused space.

  • Flexibility: They allow you to model irregular data structures, such as triangular matrices, efficiently.

7. Limitations of Jagged Arrays

  • Complexity: Jagged arrays can be more complex to manage and visualize compared to regular 2D arrays.

  • Access Validation: You must ensure that you are accessing valid indices, as different rows may have different lengths.


Conclusion

Jagged arrays in Java provide flexibility when dealing with multidimensional data where rows may have varying lengths. They are useful for representing data structures like triangular matrices, irregular tables, and more. By understanding how to declare, initialize, and manipulate jagged arrays, you can efficiently handle complex data structures in your programs.

For more Java tutorials and resources, visit codeswithpankaj.com.

Last updated