What are Jagged Arrays in Java?

What are Jagged Arrays in Java?

ยท

2 min read

A Jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. For example, we can create a 2D array where first array is of 5 elements, and is of 4 elements.

Syntax

data_type array_name[][] = new data_type[n][];  //n: no. of rows
             array_name[] = new data_type[n1] //n1= no. of colmuns in row-1
             array_name[] = new data_type[n2] //n2= no. of colmuns in row-2
             array_name[] = new data_type[n3] //n3= no. of colmuns in row-3

A simple program to demonstrate a Jagged Array.

public class JagArr
   {
   public static void main(String[] args)
      {
      int[][] twoDarray = new int[2][];

      //first row has 5 columns
      twoDarray[0] = new int[5];

      //second row has 4 columns
      twoDarray[1] = new int[4];

      int counter = 0;
      //initializing array
      for(int row=0; row < twoDarray.length; row++)
         {

         for(int col=0; col < twoDarray[row].length; col++)
            {
            twoDarray[row][col] = counter+2;
         }
      }

      //printing array
      for(int row=0; row < twoDarray.length; row++){
         System.out.println();
         for(int col=0; col < twoDarray[row].length; col++){
            System.out.print(twoarray[row][col] + " ");
         }
      }
   }
}

Output

0 2 4 6 8
10 12 14 16

See you next time<3.