Course contentsShow
← Java
Lesson 258 of 2,8706. ArraysFree lesson

Jagged Arrays: Non-Rectangular Structures

Creating arrays where each row can have a different length; understanding ragged arrays.

Jagged Arrays: Non-Rectangular Structures

What you'll learn: How to create and use arrays where each row can have a different number of columns, forming irregular "jagged" structures.

The Core Idea

In the previous lessons, you saw 2D arrays that were perfectly rectangular—every row had the same number of columns. But Java doesn't require this! Since a 2D array is actually "an array of arrays," each row can be a different length. These are called jagged arrays (or ragged arrays).

Think of it like seating arrangements: a rectangular array is like a theater with uniform rows, but a jagged array is like stadium seating where different sections have different numbers of seats.

Creating Jagged Arrays

You can create jagged arrays by initializing each row separately:

int[][] jaggedArray = new int[3][];  // 3 rows, but columns unspecified
jaggedArray[0] = new int[2];         // First row has 2 elements
jaggedArray[1] = new int[4];         // Second row has 4 elements
jaggedArray[2] = new int[1];         // Third row has 1 element

Or use an initializer list:

int[][] scores = {
    {10, 20},           // Row 0: 2 elements
    {30, 40, 50, 60},   // Row 1: 4 elements
    {70}                // Row 2: 1 element
};

Why Jagged Arrays Matter

Jagged arrays save memory when you have naturally irregular data. For example, storing student quiz scores where different students took different numbers of quizzes—you don't waste space on unused array slots.

When iterating, you must check each row's individual length:

for (int i = 0; i < scores.length; i++) {
    for (int j = 0; j < scores[i].length; j++) {  // Use scores[i].length, not a fixed value
        System.out.print(scores[i][j] + " ");
    }
}

Key Takeaway: Jagged arrays are 2D arrays where each row can have a different length, created by independently sizing each sub-array—perfect for non-uniform data structures.