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.
The most common idiom to create a two-dimensional array with 5 rows and 10 columns is:
Alternatively, you could use the following, which is more similar to what you have, though you need to explicitly initialize each row:
It is also possible to declare it the following way. It's not good design, but it works.
Enjoy!
In Java, a two-dimensional array can be declared as the same as a one-dimensional array. In a one-dimensional array you can write like
where int is a data type, array[] is an array declaration, and
new array
is an array with its objects with five indexes.Like that, you can write a two-dimensional array as the following.
Here
array
is an int data type. I have firstly declared on a one-dimensional array of that types, then a 3 row and 4 column array is created.In your code
means that you have created a two-dimensional array, with five rows. In the first row there are 10 columns. In Java you can select the column size for every row as you desire.
We can declare a two dimensional array and directly store elements at the time of its declaration as:
Here int represents integer type elements stored into the array and the array name is 'marks'. int is the datatype for all the elements represented inside the "{" and "}" braces because an array is a collection of elements having the same data type.
Coming back to our statement written above: each row of elements should be written inside the curly braces. The rows and the elements in each row should be separated by a commas.
Now observe the statement: you can get there are 3 rows and 5 columns, so the JVM creates 3 * 5 = 15 blocks of memory. These blocks can be individually referred ta as:
NOTE:
If you want to store n elements then the array index starts from zero and ends at n-1. Another way of creating a two dimensional array is by declaring the array first and then allotting memory for it by using new operator.
By combining the above two we can write: