Consider:
int[][] multD = new int[5][];
multD[0] = new int[10];
Is this how you create a two-dimensional array with 5 rows and 10 columns?
I saw this code online, but the syntax didn't make sense.
Consider:
int[][] multD = new int[5][];
multD[0] = new int[10];
Is this how you create a two-dimensional array with 5 rows and 10 columns?
I saw this code online, but the syntax didn't make sense.
Try this way:
These types of arrays are known as jagged arrays in Java:
In this scenario each row of the array holds the different number of columns. In the above example, the first row will hold three columns, the second row will hold two columns, and the third row holds five columns. You can initialize this array at compile time like below:
You can easily iterate all elements in your array:
Try the following:
... which is a short hand for something like this:
Note that every element will be initialized to the default value for
int
,0
, so the above are also equivalent to:You can create them just the way others have mentioned. One more point to add: You can even create a skewed two-dimensional array with each row, not necessarily having the same number of collumns, like this:
Try:
Note that in your code only the first line of the 2D array is initialized to 0. Line 2 to 5 don't even exist. If you try to print them you'll get
null
for everyone of them.