Why is this Java 2D array not throwing IndexOutOfBoundException?

Viewed 330

I am initializing a 2D array, specifying both number of rows and columns. I expected it to throw an error if I insert more items than the number declared in initialization, but the code works fine.

static void arrayChecks(){
    int[][] arr = new int[2][2];
    arr[0] = new int[]{1,2};
    arr[1] = new int[]{3,4,5};   //adding 3 items to a 2-column row. No exception thrown
    //arr[2] = new int[]{6,7};   //throws ArrayIndexOutOfBoundsException as expected.
    for(int[] a : arr){
        for(int i : a){
            System.out.print(String.valueOf(i));
        }
    }
    //output = 12345
}
5 Answers
Related