Jagged arrays in java

Jagged arrays are also known as ragged arrays. They are the arrays containing arrays of different length.

Consider the below example in which each row consists of different number of elements. First row contains 4 elements, second row contains 2 elements and third row contains 3 elements.

Example

package com.w3schools;
 
import java.util.Arrays;
 
public class Test {
	public static void main(String args[]){
		int[][] jaggedArray = new int[3][];
		jaggedArray[0] = new int[]{0,1,2,3};
		jaggedArray[1] = new int[]{4,5};
		jaggedArray[2] = new int[]{6,7,8};
 
		for(int[] row : jaggedArray){
			System.out.println(Arrays.toString(row));
		}
	}
}

Output

[0, 1, 2, 3]
[4, 5]
[6, 7, 8]

Interview Questions on Arrays