Jagged Arrays Varying Column Size Arrays

Jagged Arrays Varying Column Size Arrays

Jagged Arrays Varying Column Size Arrays

Summary: In this tutorial "Jagged Arrays Varying Column Size Arrays", you will learn how to create arrays with different column sizes.

It is a new feature supported by Java. In Jagged arrays, each row, in a two-dimensional array, may contain different lengths. Let us design a two-dimensional array with 4 rows where the first row contains 4 elements, the second row with 1 element, the third row with 2 elements and the fourth row with 3 elements.

Following is the schematic representation of the array.

Jagged Arrays Varying Column Size Arrays

Jagged array - Varying columns

Let us first declare the array and then assign the elements.

Jagged Arrays Varying Column Size Arrays

Output screen of JaggedArrays.java

int student[][] = new int[4][];

In the student array, rows are 4 and the columns are missing; it is done knowingly as each row should contain different lengths. Java allows to assign the row length for each individually as follows.

student[0] = new int[4];
student[1] = new int[1];
student[2] = new int[2];
student[3] = new int[3];

In the above four statements, sizes are given differently. The lengths of 4 rows are 4, 1, 2 and 3. This assignment for each row is not possible in C/C++. Values are assigned separately for each row elements.

Note: Assigning a value for an element that does not exist raises an exception at runtime – ArrayIndexOutOfBoundsException. But, program compiles.

  • student.length prints the number of rows in student array.
  • student[3].length prints the number of elements in 3rd row (indexing starts from 0).
  • student[3][1] returns the element value of 3rd row and 1st column.
  • student[i].length returns the number of elements in each row and this varies row from row.
The above array can be initialized as follows.

2 thoughts on “Jagged Arrays Varying Column Size Arrays

Leave a Reply

Your email address will not be published. Required fields are marked *