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]);
            }
        }
    }
}

3 Answers 3

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++) {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.