0

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]);
            }
        }
    }
}
Maroun
  • 94,125
  • 30
  • 188
  • 241
Sima R
  • 3
  • 1
  • 1
  • 2

3 Answers3

5

The problem is that with the loop, written like this, you assume that the nested arrays are all of length of 4 (and they are not). You'd better do:

for (int i=0; i < array1.length;i++) {
    for (int j=0; j < array1[i].length;j++) {
        ...
    }
}
Maroun
  • 94,125
  • 30
  • 188
  • 241
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
2

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);
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

2 points regarding the following solution (and the other similar answers):

for (int i=0; i < array1.length;i++) {
    for (int j=0; j < array1[i].length;j++) {
        ...
    }
}
  • Here it wont make much difference, as the code is very short, but for better performance you should always avoid repeated calculations if the result never changes. array1's length wont change so calculating its length every iteration is not efficient. This would be improved solution.

    int array1Length = array1.length;
    
    for (int i=0; i < array1Length;i++){
    
            int array1InnerLength = array1[i].length;
    
            for (int j=0; j < array1InnerLength;j++){
                    ...
            }
    }
    
  • Some people may suggest using ++j / ++i instead of i++ and j++ for better performance, you can read more about it here: What is the difference between ++i and i++?. Its not that critical imo, but it improves understanding of the code you're writing.

Cerberussian
  • 121
  • 2
  • 6