CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Arrays

Arrays
Two-dimensional arrays
Jagged

How to work with jagged arrays

  • A jagged array is a two-dimensional array whose rows have different numbers of columns.
  • When you create a jagged array, you specify the number of rows in the array, but you leave the size of each column array unspecified and set it later.

The syntax for creating a jagged array

type[][] arrayName = new type[rowCount][];

Code that creates a jagged array of integers

int[][] triangleArray = new int[5][];
triangleArray[0] = {1, 2, 3, 4, 5};
triangleArray[1] = {2, 3, 4, 5};
triangleArray[2] = {3, 4, 5};
triangleArray[3] = {4, 5};
triangleArray[4] = {5};

int[][] triangleArray = {
  {1, 2, 3, 4, 5},
  {2, 3, 4, 5},
  {3, 4, 5},
  {4, 5},
  {5}
};

triangleArray.length is 5
triangleArray[0].length is 5
triangleArray[1].length is 4
triangleArray[2].length is 3
triangleArray[3].length is 2
triangleArray[4].length is 1

Code that creates and initializes a jagged array of strings

String[][] titles =
    {{"War and Peace", "Wuthering Heights", "1984"},
     {"Casablanca", "Wizard of Oz", "Star Wars", "Birdy"},
     {"Blue Suede Shoes", "Yellow Submarine"}};

Code that creates and initializes a jagged array of integers

int number = 0;
int[][] pyramid = new int[4][];
for (int i = 0; i < pyramid.length; i++)
{
    pyramid[i] = new int[i+1];
    for (int j = 0; j < pyramid[i].length; j++)
        pyramid[i][j] = number++;
}

Code that prints the contents of the jagged array of integers

for (int i = 0; i < pyramid.length; i++)
{
   for (int j = 0; j < pyramid[i].length; j++)
      System.out.print(pyramid[i][j] + " ");
   System.out.print("\n");
}

The console output

0
1 2
3 4 5
6 7 8 9

Code that uses foreach loops to print a jagged array

for (int[] row : pyramid)
{
    for (int col : row)
        System.out.print(col + " ");
    System.out.print("\n");
}
Previous | Introduction | Rectangular | Jagged