Ragged (Jagged) Arrays in Java

When Arrays Don't Have to Be Rectangular!

CPCS203 - Object-Oriented Programming | Week 1

1 The Story: A University Registration Problem

🎓 The Scenario

You are building a registration system for King Abdulaziz University. You need to store the courses each student is enrolled in. Here's the challenge:

  • Ahmed is a full-time student taking 5 courses
  • Sara is working part-time and taking only 2 courses
  • Mohammed is in his final semester with just 3 courses
  • Fatima is an ambitious student taking 6 courses

How do you store this data efficiently?

Approach 1: Using a Regular 2D Array

Your first thought might be: "I'll create a 2D array with enough columns for the maximum number of courses!"

RegularArray.java
1// 4 students, maximum 6 courses each
2String[][] courses = new String[4][6];
3
4// Ahmed's 5 courses
5courses[0][0] = "CPCS203"; courses[0][1] = "CPCS204";
6courses[0][2] = "MATH201"; courses[0][3] = "PHYS101";
7courses[0][4] = "ENGL101";
8// courses[0][5] is null - WASTED!
9
10// Sara's 2 courses
11courses[1][0] = "CPCS203"; courses[1][1] = "MATH201";
12// courses[1][2] to courses[1][5] are null - 4 WASTED!
Regular 2D Array: Lots of Wasted Space!
[0] [1] [2] [3] [4] [5] Ahmed [0] CPCS203 CPCS204 MATH201 PHYS101 ENGL101 null Sara [1] CPCS203 MATH201 null null null null Mohammed [2] CPCS301 CPCS302 CPCS399 null null null Fatima [3] CPCS203 CPCS204 MATH201 PHYS101 CHEM101 ENGL102 1 wasted 4 wasted! 3 wasted 0 wasted Total: 8 wasted!
The Problem with Regular 2D Arrays
  • Memory waste: We allocated 24 cells (4×6) but only used 16. That's 33% wasted memory!
  • Confusion: How do we know which cells are "real" data and which are just empty?
  • Scalability: What if one student takes 10 courses? We'd need to make ALL rows have 10 columns!

The Solution: Ragged Arrays!

Remember: 2D Array = Array of Arrays!

Since a 2D array is actually an array of references, where each reference points to a separate 1D array, we can make each 1D array a different size!

This is called a Ragged Array (or Jagged Array) - the "edges" are not straight like a rectangle!

2 Understanding Ragged Arrays

Definition

A Ragged Array is a 2D array where each row can have a different number of columns. This is possible because in Java, a 2D array is an array of independent 1D arrays - each can be created with its own size!

Ragged Array: Each Student Has Exactly the Courses They Need!
STACK courses 0x10 HEAP 0x10 [0] Ahmed 0x100 [1] Sara 0x200 [2] Mohammed 0x300 [3] Fatima 0x400 0x100 - Ahmed (5 courses) CPCS203 CPCS204 MATH201 PHYS101 ENGL101 0x200 - Sara (2 courses) CPCS203 MATH201 0x300 - Mohammed (3 courses) CPCS301 CPCS302 CPCS399 0x400 - Fatima (6 courses) CPCS203 CPCS204 MATH201 PHYS101 CHEM101 ENGL102 Perfect! 16 cells used 0 wasted!
Regular 2D Array

4 × 6 = 24 cells allocated

Only 16 used

8 cells wasted (33%)

Ragged Array

5 + 2 + 3 + 6 = 16 cells allocated

All 16 used

0 cells wasted (0%)

3 Creating 2D Ragged Arrays

There are two ways to create ragged arrays:

Method 1: Step by Step (Most Clear)

1
Create the Array of References Only
Step1.java
1// Create array of 4 references (no second dimension yet!)
2String[][] courses = new String[4][];  // Note: no second dimension!
3
4// At this point:
5// courses[0] = null
6// courses[1] = null
7// courses[2] = null
8// courses[3] = null
2
Create Each Row with Different Sizes
Step2.java
1// Ahmed takes 5 courses
2courses[0] = new String[5];
3
4// Sara takes 2 courses
5courses[1] = new String[2];
6
7// Mohammed takes 3 courses
8courses[2] = new String[3];
9
10// Fatima takes 6 courses
11courses[3] = new String[6];
3
Fill in the Data
Step3.java
1// Fill Ahmed's courses
2courses[0][0] = "CPCS203";
3courses[0][1] = "CPCS204";
4courses[0][2] = "MATH201";
5courses[0][3] = "PHYS101";
6courses[0][4] = "ENGL101";
7
8// Fill Sara's courses
9courses[1][0] = "CPCS203";
10courses[1][1] = "MATH201";
11
12// ... and so on

Method 2: Direct Initialization (Shorthand)

DirectInitialization.java
1String[][] courses = {
2    {"CPCS203", "CPCS204", "MATH201", "PHYS101", "ENGL101"},  // Ahmed: 5
3    {"CPCS203", "MATH201"},                                      // Sara: 2
4    {"CPCS301", "CPCS302", "CPCS399"},                          // Mohammed: 3
5    {"CPCS203", "CPCS204", "MATH201", "PHYS101", "CHEM101", "ENGL102"}  // Fatima: 6
6};

4 Working with Ragged Arrays

Important: Each Row Has Different Length!

When iterating through a ragged array, you must use array[i].length for each row, NOT a fixed column size!

IteratingRagged.java
 1String[][] courses = {
 2    {"CPCS203", "CPCS204", "MATH201", "PHYS101", "ENGL101"},
 3    {"CPCS203", "MATH201"},
 4    {"CPCS301", "CPCS302", "CPCS399"},
 5    {"CPCS203", "CPCS204", "MATH201", "PHYS101", "CHEM101", "ENGL102"}
 6};
 7
 8String[] names = {"Ahmed", "Sara", "Mohammed", "Fatima"};
 9
10// Print all students and their courses
11for (int i = 0; i < courses.length; i++) {
12    System.out.println(names[i] + " is taking " + courses[i].length + " courses:");
13    
14    // IMPORTANT: Use courses[i].length, NOT a fixed number!
15    for (int j = 0; j < courses[i].length; j++) {
16        System.out.println("  - " + courses[i][j]);
17    }
18    System.out.println();
19}
Output
Ahmed is taking 5 courses:
  - CPCS203
  - CPCS204
  - MATH201
  - PHYS101
  - ENGL101

Sara is taking 2 courses:
  - CPCS203
  - MATH201

Mohammed is taking 3 courses:
  - CPCS301
  - CPCS302
  - CPCS399

Fatima is taking 6 courses:
  - CPCS203
  - CPCS204
  - MATH201
  - PHYS101
  - CHEM101
  - ENGL102
Common Mistake!

If you try to access an index that doesn't exist (e.g., courses[1][4] when Sara only has 2 courses), you will get an ArrayIndexOutOfBoundsException!

5 3D Ragged Arrays

🏫 Extended Scenario: Multiple Departments

Now imagine the university has multiple departments, each with a different number of students, and each student takes a different number of courses:

  • Computer Science Department: 2 students (Ahmed: 3 courses, Sara: 2 courses)
  • Mathematics Department: 3 students (Ali: 4 courses, Nora: 2 courses, Omar: 3 courses)

A 3D ragged array can handle this perfectly - each dimension can have different sizes!

Ragged3D.java
 1// 3D Ragged Array: Departments → Students → Courses
 2String[][][] university = {
 3    // Computer Science Department (2 students)
 4    {
 5        {"CPCS203", "CPCS204", "CPCS301"},    // Ahmed: 3 courses
 6        {"CPCS203", "CPCS205"}                 // Sara: 2 courses
 7    },
 8    // Mathematics Department (3 students)
 9    {
10        {"MATH201", "MATH202", "MATH301", "MATH302"},  // Ali: 4 courses
11        {"MATH201", "STAT201"},                          // Nora: 2 courses
12        {"MATH101", "MATH102", "MATH201"}               // Omar: 3 courses
13    }
14};
3D Ragged Array: university[2][?][?] - Each Level Has Different Sizes!
STACK university 0x10 HEAP 0x10 (Depts) [0] CS 0x100 [1] Math 0x200 CS Dept (0x100) - 2 students [0] Ahmed 0x1A [1] Sara 0x1B 0x1A (3 courses) CPCS203 CPCS204 CPCS301 0x1B (2 courses) CPCS203 CPCS205 Math Dept (0x200) - 3 students [0] Ali 0x2A [1] Nora 0x2B [2] Omar 0x2C 0x2A (4 courses) MATH201 MATH202 MATH301 MATH302 0x2B (2 courses) MATH201 STAT201 0x2C (3 courses) MATH101 MATH102 MATH201 Structure Summary university.length = 2 depts university[0].length = 2 students university[1].length = 3 students university[0][0].length = 3 courses university[0][1].length = 2 courses Every level is different!
Iterating3DRagged.java
 1String[] deptNames = {"Computer Science", "Mathematics"};
 2
 3// Iterate through all departments
 4for (int d = 0; d < university.length; d++) {
 5    System.out.println(deptNames[d] + " Department:");
 6    
 7    // Iterate through students in this department
 8    for (int s = 0; s < university[d].length; s++) {
 9        System.out.print("  Student " + s + ": ");
10        
11        // Iterate through courses for this student
12        for (int c = 0; c < university[d][s].length; c++) {
13            System.out.print(university[d][s][c] + " ");
14        }
15        System.out.println();
16    }
17    System.out.println();
18}

6 Summary

Key Takeaways
  1. Ragged arrays save memory by only allocating the space that's actually needed
  2. Ragged arrays are possible because multi-dimensional arrays in Java are "arrays of arrays" - each inner array is independent
  3. Always use array[i].length when iterating - each row can have different size!
  4. Create ragged arrays step-by-step: First create the array of references, then create each row with its own size
  5. 3D ragged arrays allow even more flexibility - every dimension can have different sizes
Real-World Applications
  • Student registration systems - different students, different courses
  • Social media - different users have different numbers of friends/followers
  • E-commerce - different orders have different numbers of items
  • Game development - different levels have different map sizes
  • Text processing - different paragraphs have different numbers of words
Connection to Data Structures

Understanding ragged arrays is excellent preparation for linked lists and graphs in Data Structures! These structures also use the concept of nodes connected by references, where each node can have a different number of connections.