3

I have a 2D array where no. of rows is 1 and no. of columns is > 1.

double[][] T = new double[1][24];
System.out.println(T[1].length);

But when i print the length of the columns, its says the index is out of bounds.

but when i print the following,

System.out.println(T[0].length);

I get the result as 24. But shouldn't T[0] should be equal to 1 and T[1] be equal to 24? Why am I getting this error? I suppose, java considers the above array as 1D array since it has only one row. but I need it to be a 2D array for further processes. Could anyone please help?

8 Answers 8

6

Array indices are 0-based.

If your array length is 1 (for the 1st dimension here), then you can only reference element 0.

In other words:

  • The declaration states the desired size (1 here)
  • The element reference states the desired 0-based index (0 here)
Sign up to request clarification or add additional context in comments.

Comments

2

Array indices start from 0.

Your array length is 1, so T[0] is a valid index but T[1] is not.

Comments

2
System.out.println(T[0].length);

is correct. Because Array index starts from 0

Comments

1

Array is zero based so when double[][] T = new double[1][24]; you created a 2d array first dimension is 1 and the second is 24 so that's 1*24 Array

So System.out.println(T[1].length); gave you java.lang.arrayindexoutofboundsexception As arrays are zero based

if you wrote this double[][] T = new double[3][24]; you got 3*24 Array :-

System.out.println(T[0].length);//24
System.out.println(T[1].length);//24
System.out.println(T[2].length);//24
System.out.println(T[3].length);//java.lang.arrayindexoutofboundsexception

Comments

1

Array index starts from 0.

double[][] T = new double[1][24];

which can be also declared as follows:

double[][] T = new double[1][];
T[0] = new double[24];

Comments

1

imagine matrix of 1X24. you don't have 2nd column so obvious it will through nullpointerException.

Comments

1

In Java/Android and many other languages this is how is declared

matrix[numRows][numColumns] 

And since Array indices start from 0 you need to be carefull to be sure that you are accessing a single value

x = matrix[0][1]  

Or if you are accesing the first row (as a single dimension array)

x = matrix[0]

Comments

1

Array index start with 0 not 1.

If your array length is 1 then you can start from 0. so T[0] is a valid index but T[1] is not

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.