Reputation: 47
Can you please help me understand what the following code means and what the value of number[2][2]
is?
public static void main(String[] args) {
int[][] numbers = new int [3][3];
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[0].length; j++) {
numbers[i][j] = i*j;
}
Upvotes: 0
Views: 48
Reputation: 46
In Java, a multiple dimension array is constructed with multiple one dimensional arrays. In your example numbers[3][3]
will look like the below array:
numbers = [
[0, 0, 0],
[0, 1, 2],
[0, 2, 4]
]
Now when you ask what will be the length of numbers[0]
? Then it is easy to say 3. numbers[0]
holds [0, 0, 0]
. And if you ask what is the value of numbers[2][2]
then it is 4 ( since array index starts with 0 ).
Now here I put another example.
public class Array {
public static void main(String[] args) {
int[][] numbers = new int[3][];
numbers[0] = new int[2];
numbers[1] = new int[3];
numbers[2] = new int[4];
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
numbers[i][j] = j;
}
}
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
}
}
Here I take an array and make the internal array size differently. This array will look like this:
numbers = [
[0, 1],
[0, 1, 2],
[0, 1, 2, 3]
]
Here I create the first array with size 2, second array with size 3 and third array with size 4, put some data into it and simply print it.
I think you may now visualize what numbers[0].length
actually means.
Upvotes: 1