19

For an array in Java, we can get the length of the array with array_name.length. Similarly, how would one get the number of rows and columns of a 2D array?

0

1 Answer 1

49

Well you probably want array_name.length for getting the count of the rows and array_name[0].length for the columns. That is, if you defined your array like so:

T[][] array_name = new T[row][col];
array_name.length // row
array_name[0].length // col
Sign up to request clarification or add additional context in comments.

3 Comments

Woow! that's great! Can you please tell me the logic of expression ((array_name[0].length)) that how this returns a number of columns? I mean how is that expression returns a number of columns? I want to learn its logic. thank you
@M.Barandov a 2d array is basically just an array of arrays. An example of this is if you have a 2d array with 5 rows and 4 columns, you can initialize it like this: T[][] array_name = new T[5][4]; While it looks like it makes a 2d array with 5 rows and 4 columns, it actually makes one 1d array with 5 elements. Each element is an inner array with 4 elements: ([array1,array2,array3,array4,array5] <= each array inside main array has 4 elements). Getting the length of any of these inner arrays will return the number of "columns" in the 2d array.
@LadiOyeleye tnx a lot.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.