Reputation: 27
I'm studying 2D array right now, there is a part of 2D array I don't really understand. I will show my code and explain what part I don't understand.
My code:
public static void main(String[] args){
int[][]array={{1,2,3},{1,2,3},{1,2,3}};
}
public static printArray(int[][]a){
for(int row=0;row<a.length;row++){
for(int column=0;column<a[row].length;column++)
}
My question is for the second method of printArray
. In the second for loop,what does column<a[row].length
means?
Upvotes: 0
Views: 578
Reputation: 141
This line gives the size of each row.
You know that
So, a[0].length = a[1].length = a[2].length = 3. Use of this is to ensure that we dont go Out Of Array Bounds.
Upvotes: 1
Reputation: 2854
A 2D array means that each element of the array is itself an array. The second loop allows you to loop through each {1,2,3} array (in your case). But to do that, you need the length of each array. That's what a[row].length provides.
Upvotes: 0
Reputation: 620
That is the condition to check when the limit of each row is reached, in order to avoid an ArrayIndexOutOfBoundsException
Upvotes: 0
Reputation: 1544
Java doesn't have 2D arrays. Java has arrays of arrays. The second loop uses column < a[row].length to make sure that you don't iterate past the length of the row-th array. You need this to handle nested arrays of varying length.
Upvotes: 0