Array Index out of range exception

I want to print out the elements of this multidimensional array but I get the index out of range error.

public class test {
    public static void main(String[] args) {
        int array1[][]={{1,2,3,4},{5},{6,7}};
        for (int i=0; i<3;i++){
            for (int j=0; j<4;j++){
                System.out.println(array1[i][j]);
            }
        }
    }
}
Jon Skeet
people
quotationmark

Yes, because the second "subarray" doesn't have 4 elements. It would be better to do this dynamically:

// Note preferred syntax for array types - keep all the type info in one place.
int[][] array1 = {{1,2,3,4},{5},{6,7}};
for (int i = 0; i < array1.length; i++) {
    for (int j = 0; array1[i].length; j++) {
        System.out.println(array1[i][j]);
    }
}

This way the iteration count of the inner loop depends on the array being iterated over.

An alternative is to use the enhanced for loop:

for (int[] subarray : array1) {
    for (int value : subarray) {
        System.out.println(value);
    }
}

people

See more on this question at Stackoverflow