Multi Dimensional Arrays

159 views.

The multi dimension arrays in java will be represented in the form of array of arrays.

Syntax for declaring a two dimension array

datatype arrayName[][];

Rule1

At the time of array declaration we can specify the pair of [][] either before the array name or after the array name.

int arr1[][];

int[][] arr2;

int[][]arr3;

int[] [] arr4;

int[] arr6[];

Rule2

At the time of array declaration we should not specify size of the array.

Syntax for creating 2 dimensional array

datatype arrayName[][]=new datatype[size1] [size2];

or

datatype arrayName[][];

arrayName=new datatype[size1] [size2];

 Example

int arr[][]=new int[3][4];

or

int arr[][];

arr=new int[3][4];

Rule

In a multi dimension array specifying the first dimension of array is mandatory and the remaining are optional. If we are specifying dimension then they must be specified in the order from left to right.

Jagged array:

In multi dimension array of the arrays have unequal size they called jagged array.

 

Example:

Creation of the above jagged array

int[][] arr=new int [3][];

arr[0]=new int[3];

arr[1]=new int[2];

arr[2]=new int[4];

Example

Output:

1
2
3

4
5
6

7
8
9

1
2
3

4
5
6

7
8
9

 

Leave a Reply