Need some explanation on 2D String arrays

arrays, eclipse, java

Solution

You're dealing with a 2D array. `array.length` essentially gives you the number of rows, but `array[0].length` gives the number of columns (at least for non-jagged arrays). Take this example:

String[][] array = new String[][]{
    {"1","2"},
    {"3","4"},
    {"5","6"}
};

Here `array.length` is `3` (the entire 2D-array is composed of three 1D-arrays), but `array[0].length` is `2` (the length of each constituent array). Your first `for`-loop loops over the whole array-of-arrays, but your second loops over each constituent array that is encountered by the outer loop. Therefore, the inner loop should only loop up to (but not including) `array[0].length`.

Problem

In the nested `for` loop for a basic 2D String array I came across this: ``` array = new String [5][10]; for(int i=0; i<array.length;i++) { for(int j=0; j<array[0].length;j++) { System.out.print(array[i][j]="*"); } System.out.println(""); } ``` Now this is what I want to know, why does the second `for` statement include `array[0].length` rather than `array.length` like in the `for` statement before it? All I could extract from this while experimenting was if both `for` statements contained `array.length` and the 2D array was a 5x10, it would print it as a 5x5, but with `array[0].length` it would print a correct 5x10. So why does this little adjustment fix everything?

Original source

Related problems