How do I get the second dimension of an array if I don't know it? array.length
gives only the first dimension.
For example, in
public class B { public static void main(String [] main){ int [] [] nir = new int [2] [3]; System.out.println(nir.length); } }
how would I get the value of the second dimension of nir
, which is 3.
Thanks
The length of 2d array in Java is the number of rows present in it. We check for the number of rows because they are fixed. Columns may vary per row, hence we cannot rely on that. Thus to determine the length of the two-dimensional array we count the rows in it.
To find the length of an array, use array data member 'length'. 'length' gives the number of elements allocated, not the number inserted. Write a class with a main method that creates an array of 10 integers and totals them up.
Size of a matrix = number of rows × number of columns. It can be read as the size of a matrix and is equal to number of rows “by” number of columns.
which 3?
You've created a multi-dimentional array. nir
is an array of int arrays; you've got two arrays of length three.
System.out.println(nir[0].length);
would give you the length of your first array.
Also worth noting is that you don't have to initialize a multi-dimensional array as you did, which means all the arrays don't have to be the same length (or exist at all).
int nir[][] = new int[5][]; nir[0] = new int[5]; nir[1] = new int[3]; System.out.println(nir[0].length); // 5 System.out.println(nir[1].length); // 3 System.out.println(nir[2].length); // Null pointer exception
In the latest version of JAVA this is how you do it:
nir.length //is the first dimension nir[0].length //is the second dimension
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With