Jagged Arrays
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
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();
}
}
}Student 1 (4 subjects): 78 85 90 72
Student 2 (2 subjects): 88 91
Student 3 (3 subjects): 65 70 80How it works
- Lines 3 to 6 give each row its own number of values.
- Line 8 loops over the rows;
scores[r].lengthgives that row's length. - 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:
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);
}
}
}Coach 1: 72 berths
Coach 2: 64 berths
Coach 3: 18 berthsnew 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
- 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.
- Harder: Build Pascal's triangle with 5 rows as a jagged array, where row
ihasi + 1numbers, and print it.
Key Takeaways
Was this tutorial helpful?