Two dimensional array in java
To declare an 2D array in java we use the following syntax
Datatype [][] arrayName=new Datatype[rows][cols]
If you want to declare any primitive 2D array.
int [][] ages=new int[3][4];
double [][] prices=new double[4][4]
Array ages is a two-dimensional int array, it can store 3 rows and each row can contain 4 values (columns) total of 3*4=12 values.
similar price is a two-dimensional double array, it can store 4 rows and 4 columns total (4*4) 20 elements.
Two-dimensional array initialization
1 2 3 4 5 6 7 8 9 10 11 | int[][] ages = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[][] b = new int[2][2]; b[0][0] = 1; b[0][1] = 2; b[1][0] = 3; b[1][1] = 4; |
above are the two-dimension array declared and initialized.
Length of an array in Java
Java array provides a variable length
to find the length of a variable.4
to find the length of one dimension array we use following code
1 2 3 | int[] a={1,2,3,4,5,6}; int length=a.length; System.out.println("Length of an array is "+length); |
One dimension array length is number of elements in array
Length of the 2D array in Java
In a two-dimensional array, java length is the number of rows in 2D array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | public class ArrayEx { public static void main(String[] args) { int[][] ages = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int[][] b = new int[2][2]; b[0][0] = 1; b[0][1] = 2; b[1][0] = 3; b[1][1] = 4; double[][] prices = { {12.33, 44.20, 54.06, 41.54, 32.44}, {12.33}, {}, {32.22, 43.24, 54.22}, {44.44, 53.43, 23.12} }; System.out.println("Length of ages " + ages.length); System.out.println("Length of b " + b.length); System.out.println("Length of prices " + prices.length); } } |
1 2 3 | Length of ages 3 Length of b 2 Length of prices 5 |
To access each row length we can use the following code
1 2 3 4 5 6 7 8 9 10 | System.out.println("Length of ages[0] " + ages[0].length); System.out.println("Length of ages[1] " + ages[1].length); System.out.println("Length of ages[2] " + ages[2].length); System.out.println("Length of b[0] " + b[0].length); System.out.println("Length of b[1] " + b[1].length); System.out.println("Length of prices[0] " + prices[0].length); System.out.println("Length of prices[1] " + prices[1].length); System.out.println("Length of prices[2] " + prices[2].length); System.out.println("Length of prices[3] " + prices[3].length); System.out.println("Length of prices[4] " + prices[4].length); |
1 2 3 4 5 6 7 8 9 10 | Length of ages[0] 3 Length of ages[1] 3 Length of ages[2] 3 Length of b[0] 2 Length of b[1] 2 Length of prices[0] 5 Length of prices[1] 1 Length of prices[2] 0 Length of prices[3] 3 Length of prices[4] 3 |