Way2Java

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 array - Varying columns

Let us first declare the array and then assign the elements.
public class JaggedArrays
{
 public static void main(String args[])
 {
   int student[][] = new int[4][];    
			 		
   student[0] = new int[4];	
   student[1] = new int[1];
   student[2] = new int[2];
   student[3] = new int[3];

   System.out.println("Row count: " + student.length);      
   System.out.println("Third row size: : " + student[3].length); 
                             // 1st row
   student[0][0] = 44;
   student[0][1] = 55;
   student[0][2] = 66;
   student[0][3] = 77;
		             // 2nd row
   student[1][0] = 36;
		             // 3rd row
   student[2][0] = 87;
   student[2][1] = 97;
		             // 4th row
   student[3][0] = 68;
   student[3][1] = 78;
   student[3][2] = 88;
                                                      
   System.out.println("student[3][1] marks: " + student[3][1]);  

   System.out.println("\nMatrix Form");
           
   for(int i = 0; i < student.length; i++)     
   {
     for(int j = 0; j < student[i].length; j++)
     {
       System.out.print(student[i][j] + "\t");
     }
     System.out.println();        
   }
 }
}
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.

The above array can be initialized as follows.
int student[][] = { {44, 55, 66, 77},
	            {36},
                    {87, 97},
		    {68, 78, 88}
                  };