Java Notes
Complete guide to jagged arrays in Java covering definition, creation, memory layout, initialization techniques, real-world applications, and comparison with rectangular arrays.
What is a Jagged Array?
A jagged array (also called a ragged array or irregular array) is a multi-dimensional array where each row can have a different number of columns. Unlike a rectangular 2D array where every row has the same length, a jagged array allows rows to be of varying sizes.
Think of it like a staircase — each step (row) can have a different width (number of columns).
Visual Comparison
Rectangular Array (3×4):
| | 1 | 2 | 3 | 4 | Row 0 | 4 elements |
| | 5 | 6 | 7 | 8 | Row 1 | 4 elements |
| | 9 | 10| 11| 12| Row 2 | 4 elements |
Jagged Array:
| | 1 | 2 | Row 0 | 2 elements |
| | 3 | 4 | 5 | 6 | 7 | Row 1 | 5 elements |
| | 8 | 9 | 10| Row 2 | 3 elements |
| | 11| Row 3 | 1 element |
Why Use Jagged Arrays?
Jagged arrays are useful when:
- Rows have naturally different sizes — e.g., students in different classes have different numbers of subjects
- Memory optimization — avoid wasting memory on unused cells in a rectangular array
- Representing triangular data — Pascal's triangle, lower/upper triangular matrices
- Irregular data structures — organization hierarchy where each level has different breadth
- Variable-length records — each student might have taken a different number of exams
Memory Savings Example
If you need to store data for 100 rows where:
- 50 rows need 2 columns
- 30 rows need 5 columns
- 20 rows need 10 columns
Rectangular array: 100 × 10 = 1000 cells (many wasted) Jagged array: (50×2) + (30×5) + (20×10) = 100 + 150 + 200 = 450 cells (no waste)
Creating a Jagged Array
Step 1: Declare and Create Outer Array
At this point, jagged is an array of 4 null references — no inner arrays exist yet.
Step 2: Create Inner Arrays with Different Sizes
Complete Example
Row 0 (length 2): [1, 2] Row 1 (length 5): [3, 4, 5, 6, 7] Row 2 (length 3): [8, 9, 10] Row 3 (length 1): [11]
Memory Layout
Memory Diagram:
Key Points:
- The outer array contains references (not actual data)
- Each reference points to a separate int[] object in heap
- Inner arrays can be at any location in heap (not necessarily adjacent)
- Total memory: outer array (3 refs × 8 bytes) + inner arrays (2+4+3 ints × 4 bytes) = 24 + 36 = 60 bytes (plus object headers)
Initialization Methods
Method 1: Array Literal
public class JaggedLiteral {
public static void main(String[] args) {
int[][] jagged = {
{1, 2},
{3, 4, 5, 6, 7},
{8, 9, 10},
{11}
};
for (int[] row : jagged) {
System.out.println(java.util.Arrays.toString(row));
}
}
}[1, 2] [3, 4, 5, 6, 7] [8, 9, 10] [11]
Method 2: Using Loop with Varying Sizes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Method 3: User Input
Enter number of rows: 3 Enter number of columns for row 0: 2 Enter 2 elements: 10 20 Enter number of columns for row 1: 4 Enter 4 elements: 30 40 50 60 Enter number of columns for row 2: 3 Enter 3 elements: 70 80 90 Jagged Array: Row 0: [10, 20] Row 1: [30, 40, 50, 60] Row 2: [70, 80, 90]
Traversing a Jagged Array
Important: Use row-specific length
Using for loop: 1 2 3 4 5 6 7 8 9 10 Using for-each: 1 2 3 4 5 6 7 8 9 10 Total elements: 10
Practical Applications
Application 1: Pascal's Triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1Application 2: Student Marks (Different Subjects)
Alice (3 subjects): Math: 85 Science: 92 English: 78 Average: 85.00 Bob (4 subjects): Math: 90 Science: 88 English: 76 Art: 95 Average: 87.25 Charlie (2 subjects): Math: 72 English: 80 Average: 76.00
Application 3: Lower Triangular Matrix
Lower Triangular Matrix: 1 0 0 0 2 3 0 0 4 5 6 0 7 8 9 10 Actual jagged storage: [1] [2, 3] [4, 5, 6] [7, 8, 9, 10]
Finding Maximum in Jagged Array
Maximum value: 90 Found at position: [1][2]
Jagged Array vs Rectangular Array
| Feature | Rectangular Array | Jagged Array |
|---|---|---|
| Declaration | new int[3][4] | new int[3][] + individual rows |
| Row lengths | All rows same length | Rows can differ |
| Memory | May waste memory | Memory efficient |
| Access speed | Slightly faster (predictable) | Same O(1) per element |
| Use case | Matrices, grids | Irregular data |
| Creation | Single statement | Multiple statements |
| null rows possible | No | Yes (until initialized) |
Common Mistakes
1. Accessing Uninitialized Row
2. Assuming All Rows Have Same Length
3. Using deepToString vs toString
int[][] jagged = {{1,2}, {3,4,5}};
// System.out.println(java.util.Arrays.toString(jagged)); // Shows references!
System.out.println(java.util.Arrays.deepToString(jagged)); // Shows values!4. Forgetting to Check for Null Rows
5. Specifying Second Dimension in Declaration
Best Practices
- Always check for null rows before accessing elements
- Use
jagged[i].lengthfor the inner loop bound (never hardcode or use row 0's length) - Use array literals when data is known at compile time
- Document row size logic — explain why rows have different sizes
- Consider ArrayList<int[]> if number of rows is also dynamic
- Initialize all rows immediately after creating the outer array
- Use for-each when you don't need the index for cleaner code
- Use
Arrays.deepToString()for debugging jagged arrays - Prefer rectangular arrays unless you genuinely have variable row lengths
- Keep track of total elements if needed for algorithms
Interview Questions
Q1: What is a jagged array? A jagged array is a multi-dimensional array where each row can have a different number of columns. It's implemented as an array of references to arrays of varying lengths.
Q2: How is a jagged array different from a rectangular 2D array? In a rectangular array (new int[3][4]), all rows have the same number of columns. In a jagged array (new int[3][]), each row is independently sized.
Q3: How do you get the length of a specific row? Use jagged[rowIndex].length. Each row is an independent array with its own length property.
Q4: What happens if you access a row that hasn't been initialized? You get a NullPointerException because uninitialized rows are null.
Q5: Can you create a jagged array with array literal syntax? Yes: int[][] j = {{1,2}, {3,4,5}, {6}}; — the compiler infers different row sizes.
Q6: What is the memory advantage of jagged arrays? They avoid allocating memory for unused cells. If different rows need different sizes, a rectangular array wastes space on padding.
Q7: How do you find the total number of elements in a jagged array? Sum up jagged[i].length for all rows: for(int[] row : jagged) total += row.length;
Q8: Can a jagged array have null rows? Yes. After new int[3][], all three rows are null until individually initialized.
Q9: What are practical use cases for jagged arrays? Pascal's triangle, triangular matrices, student-subject mapping (varying subjects per student), organizational hierarchies, and sparse data storage.
Q10: How do you deep-copy a jagged array? Loop through each row and clone or copy individually: for(int i=0; i<src.length; i++) dest[i] = src[i].clone();
Q11: Is int[][] a jagged or rectangular array in Java? In Java, ALL 2D arrays are technically jagged (arrays of references). new int[3][4] just happens to initialize all rows with the same length, but you could reassign any row to a different size.
Q12: How do you sort each row of a jagged array independently? Use Arrays.sort(jagged[i]) in a loop for each row.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Jagged Array in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, arrays, jagged
Related Java Master Course Topics