← Back to Chapters

Jagged Arrays in Java

? Jagged Arrays in Java

? Quick Overview

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.

? Key Concepts

  • Jagged arrays are arrays of arrays
  • Each row can have a different length
  • Declared as a 2D array but initialized row-wise
  • Commonly used when data is uneven

? Syntax / Theory

In Java, jagged arrays are created by first defining the number of rows, then allocating each row separately.

Java • Arrays • Memory Efficient

? Code Example

? View Code Example
// 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();
}

? Live Output / Explanation

Output

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.

? Interactive Visualizer

Build your own jagged array! Enter a number of columns to add a new row and observe the uneven structure.

Array is currently empty. Add a row!

? Tips & Best Practices

  • Always initialize each row before accessing it
  • Use jagged arrays when row sizes vary
  • Avoid assuming equal column length
  • Useful for dynamic or irregular datasets

? Try It Yourself

  • Create a jagged array for monthly expenses with different weeks
  • Print the total of each row separately
  • Modify the example to accept user input