javanewbie javanewbie - 4 months ago 8
Java Question

declaring a column length of 0 in a 2d array

I was just wondering if it was legal to declare a 2d ragged array with one or more of the columns having a length of 0. If it was legal, what will it actually do?

Answer

The answer is yes, it is possible. But then there's another question, why would you consider doing this? The reason I ask this is think about what you're trying to do here. An array in which the columns are of length 0 is technically an empty 2D array. I will, however, show how to do what you're asking and what will happen.

int[][] arr = new int[2][0]; //initializing a 2x0 array, which is 2 rows of size 0

or if you're trying to make a jagged array

int[][] arr = { {},{2} }; //this is a 2d array in which the first row has zero columns and the second row has one column

But what happens when you try operating on this array? You surprisingly won't get a compiler error, but you will get a runtime error. Suppose I added this line of code and tried running the program,

arr[0][0] = 1;

The error I would get is this,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 

because I can't access any elements in a 2d array with columns of size 0.