00:00

Jagged Array in Java – Explained with Examples

A jagged array (also called a ragged array) is a two-dimensional array whose rows have different lengths. It is possible because Java's 2D arrays are really arrays of arrays, and each row is a separate array object with its own size.

Jagged arrays save memory and model naturally uneven data: a different number of orders per customer, students per class, or values per row of Pascal's triangle. This tutorial shows how to create them, loop over them safely, and avoid their pitfalls.

1. What Is a Jagged Array?

Jagged array with rows of different lengths

In a regular (rectangular) 2D array every row has the same number of columns. In a jagged array the outer array holds references to rows of any length:

Rectangular vs jagged
Rectangular int[3][4]      Jagged int[3][]
[ 0 0 0 0 ]                [ 120 90 ]
[ 0 0 0 0 ]                [ 75 60 110 95 ]
[ 0 0 0 0 ]                [ 200 ]

2. Creating Jagged Arrays

Give only the number of rows (new int[3][]) and create each row separately, or write the rows directly in an initializer:

JaggedBasics.java
import java.util.Arrays;

public class JaggedBasics {
    public static void main(String[] args) {
        // Way 1: create the rows one by one
        int[][] weeklySales = new int[3][];       // 3 rows, columns not fixed yet
        weeklySales[0] = new int[] {120, 90};
        weeklySales[1] = new int[] {75, 60, 110, 95};
        weeklySales[2] = new int[] {200};

        // Way 2: initialise directly with rows of different lengths
        String[][] teams = {
                {"Asha", "Ravi", "Meera"},
                {"John"},
                {"Kiran", "Anil"}
        };

        for (int r = 0; r < weeklySales.length; r++) {
            System.out.println("store " + r + " (" + weeklySales[r].length + " values): " + Arrays.toString(weeklySales[r]));
        }
        System.out.println(Arrays.deepToString(teams));
    }
}
Output
store 0 (2 values): [120, 90]
store 1 (4 values): [75, 60, 110, 95]
store 2 (1 values): [200]
[[Asha, Ravi, Meera], [John], [Kiran, Anil]]
  • Only the first dimension must be given when creating the array.
  • Always use array[r].length for the size of row r; never assume a fixed column count.
  • Arrays.deepToString() prints any nested array, jagged or not.

3. Example: Pascal's Triangle

Pascal's triangle is a classic jagged structure: row r has r + 1 values, and each inner value is the sum of the two values above it.

PascalTriangle.java
public class PascalTriangle {
    public static void main(String[] args) {
        int rows = 6;
        int[][] pascal = new int[rows][];
        for (int r = 0; r < rows; r++) {
            pascal[r] = new int[r + 1];                  // row r has r + 1 values
            pascal[r][0] = pascal[r][r] = 1;
            for (int c = 1; c < r; c++) {
                pascal[r][c] = pascal[r - 1][c - 1] + pascal[r - 1][c];
            }
        }

        for (int[] row : pascal) {
            StringBuilder line = new StringBuilder(" ".repeat((rows - row.length) * 2));
            for (int v : row) line.append(String.format("%4d", v));
            System.out.println(line);
        }
    }
}
Output
             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1
   1   5  10  10   5   1

4. Pitfalls and Safe Looping

Two errors are typical with jagged arrays: using a row that was never created, and using an index that exists in one row but not in another.

JaggedPitfalls.java
public class JaggedPitfalls {
    public static void main(String[] args) {
        int[][] data = new int[3][];
        data[0] = new int[] {1, 2, 3};
        data[2] = new int[] {4};

        // Pitfall 1: a row that was never created is null
        try {
            System.out.println(data[1].length);
        } catch (NullPointerException e) {
            System.out.println("data[1] is null: NullPointerException");
        }

        // Pitfall 2: assuming every row has the same length
        try {
            System.out.println(data[2][1]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("data[2][1]: " + e.getMessage());
        }

        // Safe loop: check for null and use each row's own length
        int total = 0;
        for (int[] row : data) {
            if (row == null) continue;
            for (int v : row) total += v;
        }
        System.out.println("total = " + total);
    }
}
Output
data[1] is null: NullPointerException
data[2][1]: Index 1 out of bounds for length 1
total = 10

Loop with each row's own length, and skip or initialise null rows before use.

5. When to Use Jagged Arrays

  • Uneven data: monthly days (28–31), seats per row in a theatre, orders per customer.
  • Triangular data: Pascal's triangle, lower-triangular matrices, distance tables.
  • Saving memory: a rectangular array sized for the longest row wastes space in all the shorter ones.

If rows need to grow or shrink, a List<List<T>> is more flexible. For rectangular grids, a regular 2D array is simpler.

6. Jagged vs Rectangular Arrays

FeatureRectangularJagged
Row lengthsAll equalCan differ
Creationnew int[3][4]new int[3][] plus each row
MemoryMay waste space for uneven dataExactly what each row needs
Column countarr[0].length for every rowarr[r].length per row
RiskLownull rows and index errors

7. Summary

  • A jagged array is a 2D array with rows of different lengths.
  • Create it with new type[rows][] and assign each row, or with an initializer.
  • Use arr[r].length for each row, and check for null rows.
  • It suits uneven or triangular data and saves memory.

Related Tutorials