Jagged array in java

In a two-dimensional array, we can also make an array of different sizes. It means we can make a matrix of any size. These types of arrays are also known as Jagged array in java. A jagged array is an array of arrays such that member arrays can be of different sizes.

dataType nameOfArray = new Datatype[size][size];
dataType nameOfArray = new datatype[2][3];

Memory Representation after Construction

  Column 1 Column 2 Column 3
Row 1 number[0][0] number[0][1] number[0][2]
Row 2 number[1][0] number[1][1] number[1][2]

You can see in the example we define the size of the array. The first subscript size is 2 and the second subscript size is 3 which means it will create a 2X3 matrix.

Initialization of Jagged array in java

You can provide value to an array at declaration time. Here is the syntax of the initialization of the Jagged array is similar to the two-dimensional array.

dataType arrayName[][]  = { 
             {value1, value2, …valueN}, 
             {value1, value2, …valueN},
             {value1, value2, …valueN},
 };  

It’s created an array and initializes it during declaration.

int[][] number = {
			{11, 22, 33},
			{44, 55, 66},
		  };

Memory Representation after Initialization

In this example here, we are initializing a Jagged array. This array is holding the 6 elements of type int.

  Column 1 Column 2 Column 3
Row 1 number[0][0]=11 number[0][1]=22 number[0][2]=33
Row 2 number[1][0]=44 number[1][1]=55 number[1][2]=66

Jagged array is an array of array. You can see the structure of array:

Jagged array in java

Let’s take an example of a Jagged array. In which we are declaring and initializing the array.

  public class ExampleOfJaggedArray
 {  
	public static void main(String[] args)
	{
		// Creation of Array
		int[][] number;
		String[][] names;
		
		// Construction of Array
		number = new int[2][3];
		names = new String[3][3];
		
		// initilization of Array
		for(int i = 0; i < 2; i++)
		{
			for(int j = 0; j < 3; j++) 
			{
				number[i][j] = i+j;
				names[i][j] = "Hello"+i+j;
			}
		}
		
		// Accessing of Array
		for(int i = 0; i < 2; i++)
		{
			for(int j = 0; j < 3; j++) 
			{
				System.out.println(number[i][j]);
				System.out.println(names[i][j]);
			}
		}
	}  
}  

Output: 0
Hello00
1
Hello01
2
Hello02
1
Hello10
2
Hello11
3
Hello12

Leave a Comment