Jagged Arrays

Naveen AnamaneniUpdated · 4 min read

Not every table is a neat rectangle. A train has coaches with different numbers of seats: a sleeper coach has 72 berths, an AC first class coach far fewer. Students in a class may take different numbers of elective subjects. Because a Java 2D array is an array of arrays, each row can have its own length. Such an array is called a jagged (or ragged) array.

Rows of Different Lengths

Each row is its own array, so each can have its own length
Electives.java▶ Try it
public class Electives {
    public static void main(String[] args) {
        int[][] scores = {
            {78, 85, 90, 72},
            {88, 91},
            {65, 70, 80}
        };
        for (int r = 0; r < scores.length; r++) {
            System.out.print("Student " + (r + 1));
            System.out.print(" (" + scores[r].length + " subjects):");
            for (int s : scores[r]) {
                System.out.print(" " + s);
            }
            System.out.println();
        }
    }
}
Output
Student 1 (4 subjects): 78 85 90 72
Student 2 (2 subjects): 88 91
Student 3 (3 subjects): 65 70 80

How it works

  1. Lines 3 to 6 give each row its own number of values.
  2. Line 8 loops over the rows; scores[r].length gives that row's length.
  3. The inner for-each, on line 11, walks one row, however long it is.

Try it yourself: add a fourth student with just one score. Does the loop need any change?

Building Rows One at a Time

Leave the second size empty, then create each row separately:

Coaches.java▶ Try it
public class Coaches {
    public static void main(String[] args) {
        int[][] berths = new int[3][];
        berths[0] = new int[72];
        berths[1] = new int[64];
        berths[2] = new int[18];
        for (int c = 0; c < berths.length; c++) {
            System.out.printf("Coach %d: %d berths%n", c + 1, berths[c].length);
        }
    }
}
Output
Coach 1: 72 berths
Coach 2: 64 berths
Coach 3: 18 berths

new int[3][] creates the outer array with 3 empty slots (null). Each row exists only after you assign it on lines 4 to 6.

Why Bother?

A rectangular new int[3][72] would reserve 216 slots even though the three coaches need only 154. With large data, such as one row per user with a different number of orders, jagged arrays avoid wasting memory on empty slots. For data that changes size often, a list of lists (covered with collections, later in the course) is usually easier still.

Common Mistakes

Using array[0].length for every row. It's wrong as soon as rows differ, and can throw ArrayIndexOutOfBoundsException.

Forgetting to create a row. new int[3][] gives three null rows.

Writing new int[][4]. The first size is required; only the later ones may be left empty.

Practice

  1. Easy: Create a jagged array for a weekly timetable where Monday has 6 periods, Saturday 3, and the other days 5. Print each day's number of periods.
  2. Harder: Build Pascal's triangle with 5 rows as a jagged array, where row i has i + 1 numbers, and print it.

Quick check: Jagged arrays

4 questions
1What makes an array jagged?
2What does new int[3][] create?
3What should the inner loop of a jagged array use as its limit?
4Which line doesn't compile?

Key Takeaways

Was this tutorial helpful?

Lesson 72 of 482