A jagged array in Java is a 2D array where each row can have a different number of columns. Unlike a regular matrix, memory is allocated row by row, making jagged arrays flexible and memory-efficient.
In Java, jagged arrays are created by first defining the number of rows, then allocating each row separately.
Java • Arrays • Memory Efficient
// Creating and initializing a jagged array in Java
int[][] marks = new int[3][];
marks[0] = new int[]{85, 90};
marks[1] = new int[]{70, 75, 80};
marks[2] = new int[]{60};
for (int i = 0; i < marks.length; i++) {
for (int j = 0; j < marks[i].length; j++) {
System.out.print(marks[i][j] + " ");
}
System.out.println();
}
85 90
70 75 80
60
Each row prints a different number of elements because every inner array has a different length. This demonstrates the flexible structure of jagged arrays.
Build your own jagged array! Enter a number of columns to add a new row and observe the uneven structure.