Jagged Array in Java

Jagged Array in Java

Java support Jagged Arrays. You can have a different length for each column do not need to have same no of the column for all rows.


Example:-

public class JaggedArray {
public static void main(String ar[])
{
int[][] a=new int[2][];
a[0]=new int[2];
a[1]=new int[4];
a[0][0]=1;
a[0][1]=12;
a[1][0]=10;
a[1][1]=3;
a[1][2]=12;
a[1][3]=13;
System.out.println("length-"+a.length);
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a[i].length; k++) {
System.out.print(a[i][k]+" , ");
}
System.out.println("");
} 
}
}



Output:-

length-2
1 , 12 , 
10 , 3 , 12 , 13 ,
Curious why this happens? In Java, every 2D or 3D arrays is just an array having each element as an array. So if you create a 2D array with length 2,3 then it will create one array with length 2 and that array will have 2 different arrays with length 3 as it’s element.
Wanna know more about Arrays in java? Go here

Leave a Reply

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