Jagged Arrays

Arrays of arrays with different lengths

5 min read

What are Jagged Arrays?

Jagged arrays (also called ragged arrays) are multi-dimensional arrays where each row can have a different number of columns.

Visual Representation

// Regular 2D array (rectangular)
[1] [2] [3]
[4] [5] [6]
[7] [8] [9]

// Jagged array (irregular)
[1] [2] [3] [4]
[5] [6]
[7] [8] [9]

āœ“ Why Jagged Arrays? They save memory when rows have varying lengths and naturally represent hierarchical data.

Creating Jagged Arrays

Create the outer array first, then create each inner array individually with different sizes.

āš ļø Important: Always check array[i].length for each row when iterating, as they may differ!

Code Examples

Creating jagged arrays with different row sizes

java
1// Creating jagged arrays - Method 1
2int[][] jagged = new int[3][];    // 3 rows, columns undefined
3
4jagged[0] = new int[4];           // First row: 4 elements
5jagged[1] = new int[2];           // Second row: 2 elements
6jagged[2] = new int[3];           // Third row: 3 elements
7
8// Fill with values
9jagged[0] = new int[]{1, 2, 3, 4};
10jagged[1] = new int[]{5, 6};
11jagged[2] = new int[]{7, 8, 9};
12
13// Method 2: Direct initialization
14int[][] triangle = {
15    {1},
16    {2, 3},
17    {4, 5, 6},
18    {7, 8, 9, 10}
19};

Safe iteration handling different row lengths

java
1// Iterating jagged arrays
2int[][] jagged = {
3    {1, 2, 3, 4},
4    {5, 6},
5    {7, 8, 9}
6};
7
8// Safe iteration - check each row's length
9for (int i = 0; i < jagged.length; i++) {
10    System.out.print("Row " + i + ": ");
11    for (int j = 0; j < jagged[i].length; j++) {  // Use jagged[i].length!
12        System.out.print(jagged[i][j] + " ");
13    }
14    System.out.println();
15}
16
17// Enhanced for loop (automatically handles different lengths)
18for (int[] row : jagged) {
19    for (int value : row) {
20        System.out.print(value + " ");
21    }
22    System.out.println();
23}

Classic Pascals Triangle using jagged array

java
1// Pascal's Triangle example
2int numRows = 5;
3int[][] pascal = new int[numRows][];
4
5for (int i = 0; i < numRows; i++) {
6    pascal[i] = new int[i + 1];     // Each row has i+1 elements
7    pascal[i][0] = 1;                // First element is 1
8    pascal[i][i] = 1;                // Last element is 1
9    
10    for (int j = 1; j < i; j++) {
11        pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
12    }
13}
14
15// Print Pascal's Triangle
16for (int[] row : pascal) {
17    for (int val : row) {
18        System.out.print(val + " ");
19    }
20    System.out.println();
21}
22/*
231 
241 1 
251 2 1 
261 3 3 1 
271 4 6 4 1 
28*/

Real-world jagged array application

java
1// Practical use case: Student grades
2// Each student may have different number of assignments
3String[] students = {"Alice", "Bob", "Charlie"};
4int[][] grades = {
5    {95, 87, 92, 88},      // Alice: 4 assignments
6    {78, 85},               // Bob: 2 assignments
7    {90, 88, 76, 95, 89}   // Charlie: 5 assignments
8};
9
10// Calculate average for each student
11for (int i = 0; i < students.length; i++) {
12    int sum = 0;
13    for (int grade : grades[i]) {
14        sum += grade;
15    }
16    double avg = (double) sum / grades[i].length;
17    System.out.printf("%s: %.2f (from %d assignments)%n",
18        students[i], avg, grades[i].length);
19}
20
21// Find total elements in jagged array
22int totalElements = 0;
23for (int[] row : grades) {
24    totalElements += row.length;
25}
26System.out.println("Total grades: " + totalElements);

Use Cases

  • Pascals Triangle and mathematical patterns
  • Variable-length records (e.g., student grades)
  • Sparse data representation
  • Hierarchical data structures
  • Text storage (lines of different lengths)
  • Graph adjacency lists

Common Mistakes to Avoid

  • Assuming all rows have same length
  • NullPointerException from uninitialized rows
  • ArrayIndexOutOfBoundsException from wrong index
  • Using matrix[0].length for all rows
  • Forgetting to create individual row arrays
  • Not checking if row exists before accessing