-1

I am learning Java's Multidimensional arrays. When I set arr ={{1,2,3},{4,5,6}} and int x = arr[2 or more][any digit], the ArrayIndexOutOfBoundsException comes out.

public class Array {

    public static void main(String[] args) {

        int [][] arr= { {4,5,6,7},{1,2,3,8}};
        int x;

        for(int a= 0,b= 0;a<= 3 && b<= 3; a++, b++){
            try {
                x = arr[a][b];
                System.out.println("a = "+ a + " b = "+ b +"\n"+ x +"\nCorrect----------------------");
            }catch(ArrayIndexOutOfBoundsException e) {
                System.out.println("a = "+ a + " b = "+ b +"\nERROR------------------");
            }
        }   

    }

}

Result:

a = 0 b = 0
4
Correct----------------------
a = 1 b = 1
2
Correct----------------------
a = 2 b = 2
ERROR------------------
a = 3 b = 3
ERROR------------------
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49

2 Answers2

1

Your for loop goes through a 4x4 range, but your array is 2x4.

A 2d array is an array of arrays. The first index is which array you access.

You have two arrays, [4,5,6,7] and [1,2,3,8]

accessing arr[2] means gives me the third array, and you don't have a third array

Tyler
  • 955
  • 9
  • 20
1

int [][] arr= { {4,5,6,7},{1,2,3,8}}; defines an array of 2 int[]:

arr[0]={4,5,6,7}
arr[1]={1,2,3,8}

So arr[2] will throw the exception.

Matthieu
  • 2,736
  • 4
  • 57
  • 87