Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the length of two-dimensional array

Tags:

java

arrays

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

like image 527
Numerator Avatar asked Sep 09 '11 20:09

Numerator


People also ask

What is the length of a 2 dimensional array in Java?

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.

How can you find the length of an array?

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.

How do I find the length of a matrix?

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.


2 Answers

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 
like image 97
Brian Roach Avatar answered Sep 29 '22 03:09

Brian Roach


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 
like image 35
Rasmus Norup Avatar answered Sep 29 '22 03:09

Rasmus Norup