Zhuangzhuang Li
Zhuangzhuang Li

Reputation: 27

2D array row and column length

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].lengthmeans?

Upvotes: 0

Views: 578

Answers (4)

rpg
rpg

Reputation: 141

This line gives the size of each row.
You know that

  • a[0]={1, 2, 3}
  • a[1]={1, 2, 3}
  • a[2]={1, 2, 3}

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

Edwin Torres
Edwin Torres

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

bra_racing
bra_racing

Reputation: 620

That is the condition to check when the limit of each row is reached, in order to avoid an ArrayIndexOutOfBoundsException

Upvotes: 0

sheunis
sheunis

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

Related Questions