Java Notes
A jagged array is a two-dimensional Java array whose rows can have different lengths. It is useful when each record contains a different number of values.
A jagged array is a two-dimensional array where rows have different lengths. Java supports it naturally because a two-dimensional array is really an array of separate row arrays.
Why use a jagged array?
Use a rectangular array when every row has the same number of values. Use a jagged array when row sizes differ, such as the number of assignments completed by each student.
| Student | Completed assignments |
|---|---|
| Asha | 3 scores |
| Ravi | 2 scores |
| Meera | 4 scores |
Allocating four slots for every student would leave unused cells. A jagged array represents the data without those empty values.
Create rows of different sizes
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
new int[3][] creates space for three row references, not three complete rows. Each row is created later with its own length. The nested loop uses the actual values in each row, so it works even when lengths differ.
Short initializer form
When all values are known, write the same jagged array more compactly:
int[][] scores = {
{72, 81, 90},
{68, 75},
{84, 79, 91, 88}
};Here, scores[0].length is 3, scores[1].length is 2, and scores[2].length is 4.
Safe traversal rule
Never use scores[0].length as the column limit for every row. It fails if another row is shorter. Use the current row length instead:
What to remember
- A jagged array is an array of rows with different lengths.
- Declare it with
new int[rows][], then create each row separately. - Use
array[row].lengthduring traversal. - Choose jagged arrays when the data itself has uneven row sizes.
Continue the lesson path